Given a String, write a Python program to remove all the words with K length.
Examples:
Input : test_str = ‘Gfg is best for all geeks’, K = 3
Output : is best geeks
Explanation : Gfg, for and all are of length 3, hence removed.Input : test_str = ‘Gfg is best for all geeks’, K = 2
Output : Gfg best for all geeks
Explanation : is of length 2, hence removed.
Method #1 : Using split() + join() + list comprehension + len()
In this each word is split using split(), and then lengths are checked using len(), and then are omitted matching K. At last words are joined.
Python3
# Python3 code to demonstrate working of# Remove K length words in String# Using split() + join() + list comprehension + len() # initializing stringtest_str = 'Gfg is best for all geeks' # printing original stringprint("The original string is : " + (test_str)) # initializing KK = 3 # getting splitstemp = test_str.split() # omitting K lengthsres = [ele for ele in temp if len(ele) != K] # joining resultres = ' '.join(res) # printing resultprint("Modified String : " + (res)) |
Output:
The original string is : Gfg is best for all geeks Modified String : is best geeks
Method #2 : Using filter() + lambda + split() + len() + join()
In this, we perform task of filtering using filter() + lamnda, rest all the functionalities are similar to above method.
Python3
# Python3 code to demonstrate working of# Remove K length words in String# Using filter() + lambda + split() + len() + join() # initializing stringtest_str = 'Gfg is best for all geeks' # printing original stringprint("The original string is : " + (test_str)) # initializing KK = 3 # getting splitstemp = test_str.split() # omitting K lengths# filtering using filter() and lambdares = list(filter(lambda ele: len(ele) != K, temp)) # joining resultres = ' '.join(res) # printing resultprint("Modified String : " + (res)) |
Output:
The original string is : Gfg is best for all geeks Modified String : is best geeks
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


