Python program to remove K length words in String
Last Updated :
18 Feb, 2023
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))
OutputThe 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))
OutputThe 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))
OutputThe 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.
Similar Reads
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 program to remove Nth occurrence of the given word Given a list of words in Python, the task is to remove the Nth occurrence of the given word in that list. Examples:Â Input: list - ["geeks", "for", "geeks"] word = geeks, N = 2 Output: list - ["geeks", "for"]Input: list - ["can", "you", "can", "a", "can" "?"] word = can, N = 1 Output: list - ["you",
8 min read
Python program to Concatenate Kth index words of String Given a string with words, concatenate the Kth index of each word. Input : test_str = 'geeksforgeeks best geeks', K = 3 Output : ktk Explanation : 3rd index of "geeksforgeeks" is k, "best" has 't' as 3rd element. Input : test_str = 'geeksforgeeks best geeks', K = 0 Output : gbg Method #1 : Using joi
4 min read
Python program to remove last N characters from a string In this article, weâll explore different ways to remove the last N characters from a string in Python. This common string manipulation task can be achieved using slicing, loops, or built-in methods for efficient and flexible solutions.Using String SlicingString slicing is one of the simplest and mos
2 min read
Python Program to Group Strings by K length Using Suffix Given Strings List, the task is to write a Python program to group them into K-length suffixes. Input : test_list = ["food", "peak", "geek", "good", "weak", "sneek"], K = 3 Output : {'ood': ['food', 'good'], 'eak': ['peak', 'weak'], 'eek': ['geek', 'sneek']} Explanation : words ending with ood are f
5 min read
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 tas
5 min read
Python | Ways to remove numeric digits from given string In Python, we can remove numeric digits from a string in multiple ways. For example, if we have a string like "Geeks123" and we want to remove the numbers to get "Geeks", we can use different methods to accomplish this. We can do this by using techniques such as list comprehension, regular expressio
3 min read
Python - Remove K length Duplicates from String To remove consecutive K-length duplicates from a string iterate through the string comparing each substring with the next and excluding duplicates. For example we are given a string s = "abcabcabcabc" we need to remove k length duplicate from the string so that the output should become "aaaabc" . We
3 min read
Python program to remove the nth index character from a non-empty string Given a String, the task is to write a Python program to remove the nth index character from a non-empty string Examples: Input: str = "Stable" Output: Modified string after removing 4 th character Stabe Input: str = "Arrow" Output: Modified string after removing 4 th character Arro The first approa
4 min read