Python | Prefix extraction depending on size

Sometimes, while working with Python, we can have a problem in which we need to extract prefix from a string. This can be conditional sometimes, and we just need to extract specific length substring if size of string is larger than some N. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is brute force way to perform this task, in which we extract the string according to size using a loop.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Prefix extraction depending on size
# using loop
  
# Initializing list
test_list = ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
  
# Initializing K 
K = 2
  
# Initializing N 
N = 4
  
# printing original list
print("The original list is : " + str(test_list))
  
# Prefix extraction depending on size
# using loop
res = []
for idx in test_list:
    if len(idx) >= N:
        res.append(idx[:K])
       
# printing result 
print ("List after prefix extraction : " + str(res))

chevron_right


Output :



The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
List after prefix extraction : ['ge', 'be', 'ge']

 

Method #2 : Using filter() + lambda
This task can also be performed using combination of above functions. In this, we perform the task of checking using filter(), and extraction is done in shorter way using list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate 
# Prefix extraction depending on size
# using filter() + lambda
  
# Initializing list
test_list = ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
  
# Initializing K 
K = 2
  
# Initializing N 
N = 4
  
# printing original list
print("The original list is : " + str(test_list))
  
# Prefix extraction depending on size
# using filter() + lambda
res = [sub[:K] for sub in filter(lambda ele : len(ele) >= N, test_list)]
      
# printing result 
print ("List after prefix extraction : " + str(res))

chevron_right


Output :

The original list is : ['geeksforgeeks', 'is', 'best', 'for', 'geeks']
List after prefix extraction : ['ge', 'be', 'ge']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.