Python – Extract range characters from String

Given a String, extract characters only which lie between given letters.

Input : test_str = ‘geekforgeeks is best’, strt, end = “g”, “s”
Output : gkorgksiss
Explanation : All characters after g and before s are retained.

Input : test_str = ‘geekforgeeks is best’, strt, end = “g”, “r”
Output : gkorgki
Explanation : All characters after g and before r are retained.

Method #1 : Using list comprehension

In this, we check for character in range using comparison operation and list comprehension does task of iteration and creation of new list. Then join() can be employed to reconvert to string.



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Extract range  characters from String
# Using list comprehension
  
# initializing string
test_str = 'geekforgeeks is best'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing range letters 
strt, end = "f", "s"
  
# join() to get result in string 
res = ''.join([chr for chr in test_str if chr >= strt and chr <= end])
  
# printing result 
print("Extracted String : " + str(res)) 

chevron_right


Output

The original string is : geekforgeeks is best
Extracted String : gkforgksiss

Method #2 : Using filter() + lambda + join()

Another way to solve this, in this, we perform task of comparision using lambda, and filter() used lambda function to get required characters.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Extract range  characters from String
# Using filter() + lambda + join()
  
# initializing string
test_str = 'geekforgeeks is best'
  
# printing original string
print("The original string is : " + str(test_str))
  
# initializing range letters 
strt, end = "f", "s"
  
# join() to get result in string 
res = ''.join(list(filter(lambda chr : chr >= strt and chr <= end, test_str)))
  
# printing result 
print("Extracted String : " + str(res)) 

chevron_right


Output

The original string is : geekforgeeks is best
Extracted String : gkforgksiss



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.