Python | Remove unwanted spaces from string
Last Updated :
23 Apr, 2023
Sometimes, while working with strings, we may have situations in which we might have more than 1 spaces between intermediate words in strings that are mostly unwanted. This type of situation can occur in web development and often needs rectification. Let's discuss certain ways in which this task can be performed.
Examples:
Example 1:
Input: GfG is good website
Output: GfG is good website
Explanation: Unwanted spaces have been removed from the string.
Example 2:
Input: GfG is good website
Output: GfG is good website
Explanation: Unwanted spaces have been removed from the string.
Method #1: Using re.sub() This problem can be performed using the regex in which we can restrict the separation between the words to be just a single space using the appropriate regex string.
Python3
# Python3 code to demonstrate working of
# remove additional space from string
# Using re.sub()
import re
# initializing string
test_str = "GfG is good website"
# printing original string
print("The original string is : " + test_str)
# using re.sub()
# remove additional space from string
res = re.sub(' +', ' ', test_str)
# printing result
print("The strings after extra space removal : " + str(res))
Output : The original string is : GfG is good website
The strings after extra space removal : GfG is good website
Time Complexity: O(n)
Space Complexity: O(n)
Method #2: Using split() and join() This task can also be performed using the split and join function. This is performed in two steps. In first step, we convert the string into list of words and then join with a single space using the join function.
Python3
# Python3 code to demonstrate working of
# remove additional space from string
# Using split() + join()
# initializing string
test_str = "GfG is good website"
# printing original string
print("The original string is : " + test_str)
# using split() + join()
# remove additional space from string
res = " ".join(test_str.split())
# printing result
print("The strings after extra space removal : " + str(res))
Output : The original string is : GfG is good website
The strings after extra space removal : GfG is good website
Time Complexity: O(n)
Space Complexity: O(n)
Method #3 : Using split() with strip() and join() This task can also be performed using the split with strip and join function. This is performed in two steps. In first step, we convert the string into list of words and then join with a single space using the join function.
Python3
# Python3 code to demonstrate working of
# remove additional space from string
# Using strip() and split() + join()
# initializing string
test_str = "GfG is good website"
# printing original string
print("The original string is : " + test_str)
# using split() + join()
# remove additional space from string
res = " ".join(test_str.strip().split())
# printing result
print("The strings after extra space removal : " + str(res))
Method 4: Using a loop to iterate over each character of the string
Initialize an empty string to store the result
Use a loop to iterate over each character of the input string
If the current character is a space and the previous character was also a space, skip it
Otherwise, append the current character to the result string
Python3
# initializing string
test_str = "GfG is good website"
# printing original string
print("The original string is : " + test_str)
# using a loop to remove additional spaces
res = ""
for i in range(len(test_str)):
if i == 0 or (test_str[i] != " " or test_str[i-1] != " "):
res += test_str[i]
# printing result
print("The strings after extra space removal : " + str(res))
OutputThe original string is : GfG is good website
The strings after extra space removal : GfG is good website
Time complexity: O(n)
Auxiliary space: O(n) (to store the result string)
Similar Reads
Remove spaces from a string in Python Removing spaces from a string is a common task in Python that can be solved in multiple ways. For example, if we have a string like " g f g ", we might want the output to be "gfg" by removing all the spaces. Let's look at different methods to do so:Using replace() methodTo remove all spaces from a s
2 min read
Python - Ways to remove multiple empty spaces from string List We are given a list of strings li =["Hello world", " Python is great ", " Extra spaces here "] we need to remove all extra spaces from the strings so that the output becomes ["Hello world", "Python is great' , "Extra spaces here"] .This can be done using methods like split() and join(), regular expr
3 min read
Python - Remove substring list from String Our task is to remove multiple substrings from a string in Python using various methods like string replace in a loop, regular expressions, list comprehensions, functools.reduce, and custom loops. For example, given the string "Hello world!" and substrings ["Hello", "ld"], we want to get " wor!" by
3 min read
Python - Filter rows without Space Strings Given Matrix, extract rows in which Strings don't have spaces. Examples: Input: test_list = [["gfg is", "best"], ["gfg", "good"], ["gfg is cool"], ["love", "gfg"]] Output: [['gfg', 'good'], ['love', 'gfg']] Explanation: Both the lists have strings that don't have spaces. Input: test_list = [["gfg is
6 min read
Python | Removing Initial word from string During programming, sometimes, we can have such a problem in which it is required that the first word from the string has to be removed. These kinds of problems are common and one should be aware about the solution to such problems. Let's discuss certain ways in which this problem can be solved. Met
4 min read
How to Remove a Substring in Python? In Python, removing a substring from a string can be achieved through various methods such as using replace() function, slicing, or regular expressions. Depending on your specific use case, you may want to remove all instances of a substring or just the first occurrence. Letâs explore different ways
2 min read
Remove Special Characters from String in Python When working with text data in Python, it's common to encounter strings containing unwanted special characters such as punctuation, symbols or other non-alphanumeric elements. For example, given the input "Data!@Science#Rocks123", the desired output is "DataScienceRocks123". Let's explore different
2 min read
Python | Remove the given substring from end of string Sometimes we need to manipulate our string to remove extra information from the string for better understanding and faster processing. Given a task in which the substring needs to be removed from the end of the string using Python. Â Â Remove the substring from the end of the string using Slicing In
3 min read
Python - Remove after substring in String Removing everything after a specific substring in a string involves locating the substring and then extracting only the part of the string that precedes it. For example we are given a string s="Hello, this is a sample string" we need to remove the part of string after a particular substring includin
3 min read