Python | Remove unwanted spaces from string
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 situations can occur in web development and often needs rectification. Let’s discuss certain ways in which this task can be performed.
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 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)) |
The original string is : GfG is good website The strings after extra space removal : GfG is good website
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 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)) |
The original string is : GfG is good website The strings after extra space removal : GfG is good website
Recommended Posts:
- Python | Remove spaces from a string
- Python | Removing unwanted characters from string
- Python | Remove spaces from dictionary keys
- Python | Remove additional spaces in list
- Python | Check for spaces in string
- Python | String Split including spaces
- Python code to move spaces to front of string in single traversal
- Python | Remove the given substring from end of string
- Remove all duplicates from a given string in Python
- Ways to remove i'th character from string in Python
- Python | Ways to remove numeric digits from given string
- Python | Ways to remove n characters from start of given string
- Color Spaces in OpenCV | Python
- Python | Visualizing image in different color spaces
- Regex in Python to put spaces between words starting with capital letters
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



