Python | Extract odd length words in String
Last Updated :
01 Jun, 2023
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.
Python3
# 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))
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.
Python3
# 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))
Output : The original string is : gfg is best of geeks
The odd length strings are : ['gfg', 'geeks']
Method 3: Using enumerate function
Python3
# python code to print odd length words
n="geeks for geek"
s=n.split(" ")
print([x for i,x in enumerate(s) if len(x)%2!=0])
The Time and Space Complexity for all the methods are the same:
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4: Using join() + split() + filter() + list() + lambda functions
Python3
# Python3 code to demonstrate working of
# Extract odd length words in String
# Using join() + split() + filter() + list() + lambda functions
# 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
res = ' '.join(list(filter(lambda x: len(x) % 2 != 0, test_str.split())))
# printing result
print("The odd length strings are : " + str(res))
OutputThe original string is : gfg is best of geeks
The odd length strings are : gfg geeks
Time Complexity: O(n)
Auxiliary Space: O(n)
Method : Using Recursion
Python3
# Python3 code to demonstrate working of
# Extract odd length words in String
#recursive function to print odd length words
def oddLengthWords(itr,list1,word=''):
if itr == len(list1): #base condition
return word
if len(list1[itr])%2:
word=word+(list1[itr])+' '
return oddLengthWords(itr+1,list1,word)
test_str = "gfg is best of geeks"
# printing original string
print("The original string is : " + test_str)
l=[i for i in test_str.split()]
res=oddLengthWords(0,l)
# printing result
print("The odd length strings are : " + str(res))
#this code contributed by tvsk
OutputThe original string is : gfg is best of geeks
The odd length strings are : gfg geeks
Time Complexity: O(n)
Auxiliary Space: O(n)
Method : Using regular expressions
Python3
import re
# 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 regular expressions
res = [x for x in re.findall(r'\b\w{1,}\b', test_str) if len(x)%2]
# printing result
print("The odd length strings are : " + str(res))
#This code is contributed by Vinay Pinjala.
OutputThe original string is : gfg is best of geeks
The odd length strings are : ['gfg', 'geeks']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5 : Using numpy
Python3
import numpy as np
def extract_odd_length_words(string):
words = np.array(string.split())
lengths = np.vectorize(len)(words)
odd_length_indices = np.where(lengths % 2 != 0)
odd_length_words = words[odd_length_indices]
return odd_length_words
# Test
test_str = "gfg is best of geeks"
result = extract_odd_length_words(test_str)
print(result)
Output:
['gfg' 'geeks']
Time Complexity: O(n)
Auxiliary Space: O(n)
METHOD 6: Using reduce() function
Approach/Intuition:
In this approach, we use the reduce() function to iterate over the words in the input string, and filter out the words with odd length. Finally, we get a list of odd length words.
Algorithm:
- Take the input string from the user.
- Split the string into a list of words using the split() function.
- Define a lambda function to check if the length of the word is odd.
- Use the reduce() function from functools module to combine the filtered words to a single list.
- Print the list of odd length words.
Python3
from functools import reduce
input_str = "gfg is best of geeks"
word_list = input_str.split()
odd_len_words = reduce(lambda x, y: x + [y] if len(y) % 2 != 0 else x, word_list, [])
print("The odd length strings are : ['" + "', '".join(odd_len_words) + "']")
OutputThe odd length strings are : ['gfg', 'geeks']
Time Complexity: O(n), where n is the number of words in the input string.
Space Complexity: O(m), where m is the number of odd length words in the input string.
Similar Reads
Python | Extract Nth words in Strings List Sometimes, while working with Python Lists, we can have problems in which we need to perform the task of extracting Nth word of each string in List. This can have applications in the web-development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using list compreh
7 min read
Python - Words Lengths in String We are given a string we need to find length of each word in a given string. For example, we are s = "Hello world this is Python" we need to find length of each word so that output should be a list containing length of each words in sentence, so output in this case will be [5, 5, 4, 2, 6].Using List
2 min read
Python - Extract K length substrings The task is to extract all possible substrings of a specific length, k. This problem involves identifying and retrieving those substrings in an efficient way. Let's explore various methods to extract substrings of length k from a given string in PythonUsing List Comprehension List comprehension is t
2 min read
Python | Extract words from given string In Python, we sometimes come through situations where we require to get all the words present in the string, this can be a tedious task done using the native method. Hence having shorthand to perform this task is always useful. Additionally, this article also includes the cases in which punctuation
4 min read
Python - Get Nth word in given String Sometimes, while working with data, we can have a problem in which we need to get the Nth word of a String. This kind of problem has many application in school and day-day programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop This is one way in which thi
4 min read