Open In App

Python program to remove K length words in String

Last Updated : 18 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 string
test_str = 'Gfg is best for all geeks'
 
# printing original string
print("The original string is : " + (test_str))
 
# initializing K
K = 3
 
# getting splits
temp = test_str.split()
 
# omitting K lengths
res = [ele for ele in temp if len(ele) != K]
 
# joining result
res = ' '.join(res)
 
# printing result
print("Modified String : " + (res))


Output:

The original string is : Gfg is best for all geeks
Modified String : is best geeks

Time Complexity: O(n)

 Auxiliary Space: O(n)

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

In this, we perform task of filtering using filter() + lambda, 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 string
test_str = 'Gfg is best for all geeks'
 
# printing original string
print("The original string is : " + (test_str))
 
# initializing K
K = 3
 
# getting splits
temp = test_str.split()
 
# omitting K lengths
# filtering using filter() and lambda
res = list(filter(lambda ele: len(ele) != K, temp))
 
# joining result
res = ' '.join(res)
 
# printing result
print("Modified String : " + (res))


Output:

The original string is : Gfg is best for all geeks
Modified String : is best geeks

The time and space complexity for all the methods are the same:

Time Complexity : O(n)
Auxiliary Space : O(n)

Method #3: # Using split() + join() + remove() + len()

Python3




# Python3 code to demonstrate working of
# Remove K length words in String
# Using split() + join() + remove() + len()
 
# initializing string
test_str = 'Gfg is best for all geeks'
 
# printing original string
print("The original string is : " + (test_str))
 
# initializing K
K = 3
 
# getting splits
temp = test_str.split()
 
for i in temp.copy():
    if len(i) == K:
        temp.remove(i)
 
 
# joining result
res = ' '.join(temp)
 
# printing result
print("Modified String : " + (res))


Output

The original string is : Gfg is best for all geeks
Modified String : is best geeks

Time Complexity : O(n)
Auxiliary Space : O(n)

Method #4: # Using recursive method.

Python3




# Python3 code to demonstrate working of
# Remove K length words in String
# Using split() + join() + remove() + len()
 
def remove_string(start,lst,k,word=''):
  if start==len(lst):
    return word
  if len(lst[start])!=k:
    word=word+lst[start]+' '
  return remove_string(start+1,lst,k,word)
 
 
 
# initializing string
test_str = 'Gfg is best for all geeks'
 
# printing original string
print("The original string is : " + (test_str))
 
# initializing K
K = 3
 
test_str=test_str.split()
 
res=remove_string(0,test_str,K)
 
# printing result
print("Modified String : " + (res))


Output

The original string is : Gfg is best for all geeks
Modified String : is best geeks 

Time Complexity : O(n)
Auxiliary Space : O(n)

Approach #5: Using Regular Expression
 

The given program removes all the words with length K from a given input string. Here is a step-by-step approach to implement the same program:

1. Import the ‘re’ module for using regular expressions.

2. Initialize a string variable test_str with the given string.

3. Initialize a variable K with the given value.

4. Use the re.sub() method to replace all the words with length K with an empty string.

5. Split the resulting string by space using the split() method, and then join the list using the join() method to remove extra whitespaces between words.

6. Print the modified string.

Note that \b in the regular expression pattern matches a word boundary, and \w matches a word character (alphanumeric or underscore). The { and } characters in the pattern are used to specify the number of repetitions, which is taken as the value of the K variable converted to a string using str(K).

Python3




import re
 
#initializing string
test_str = 'Gfg is best for all geeks'
 
#printing original string
print("The original string is : " + (test_str))
 
#initializing K
K = 3
 
#removing words with length K
res = " ".join(re.sub(r'\b\w{'+ str(K) + r'}\b', '', test_str).split())
 
#printing result
print("Modified String : " + (res))


Output

The original string is : Gfg is best for all geeks
Modified String : is best geeks

Time Complexity: O(n), where n is the number of characters in the string.
Auxiliary Space: O(n), where n is the number of characters in the result.
In this approach, we are using the re module in python to perform regular expression operations. The ‘\b’ matches word boundaries, the ‘\w’ matches word characters and the curly braces ‘{}’ specify the number of repetitions. So, the regular expression ‘\b\w{‘+ str(K) + r’}\b’ matches all the words with length K. The ‘sub’ function replaces all the matches with an empty string.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads