Python | Extract odd length words in String

Sometimes, while working with Python, we can have a problem in which we need to extract certain length words from a string. This can be extraction of odd length words from the string. This can have application in many domains including day-day programming. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is brute force way in which this task can be performed. In this, we first split the string to words and then perform iteration to get the odd length words.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Extract odd length words in String
# Using loop
  
# initializing string
test_str = "gfg is best of geeks"
  
# printing original string
print("The original string is : " + test_str)
  
# Extract odd length words in String
# Using loop
res = []
for ele in test_str.split():
    if len(ele) % 2 :
        res.append(ele)
  
# printing result 
print("The odd length strings are : " + str(res)) 

chevron_right


Output :

The original string is : gfg is best of geeks
The odd length strings are : ['gfg', 'geeks']

 

Method #2 : Using list comprehension
This task can also be performed using list comprehension. In this, we perform the task in similar way as above. Just the difference is that its a one-liner.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Extract odd length words in String
# Using list comprehension
  
# initializing string
test_str = "gfg is best of geeks"
  
# printing original string
print("The original string is : " + test_str)
  
# Extract odd length words in String
# Using list comprehension
res = [ele for ele in test_str.split() if len(ele) % 2]
  
# printing result 
print("The odd length strings are : " + str(res)) 

chevron_right


Output :

The original string is : gfg is best of geeks
The odd length strings are : ['gfg', 'geeks']



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.