[toc]
Introduction
Have you ever come across strings in Python that have unnecessary spacing between the words or characters? If so then you are at the correct place to find the solutions to your problem. In this article, we are going to learn about the different methods to remove multiple spaces in a string. In Python, removing multiple spaces from a string means excluding all the extra whitespaces so that there remains only a single space between each word in the string.
Example: Let’s have a quick look at one of the solutions and the desired output to get an overview of the problem at hand.
import re s = "Hello and Welcome to Finxter!" print("String with multiple spaces:") print(s) print("String after removing multiple spaces:") print(re.sub(' +', ' ', s))
Output:
String with multiple spaces: Hello and Welcome to Finxter! String after removing multiple spaces: Hello and Welcome to Finxter!
Now, letβs look at the various methods to remove multiple spaces in a string.
Video Solution:
Method 1: Using Regular Expressions
The best way to remove multiple spaces in a given string in Python is to use regular expressions. You must import Python’s regular expressions library in order to utilize regular expressions within your code.
Import re |
Related article: Python Regex Superpower β The Ultimate Guide
re.sub()
The re.sub(pattern, repl, string, count=0, flags=0) method returns a new string where all occurrences of the pattern in the old string are replaced by repl.
Example: In the following example we will replace the string “Java
” with “Python
“. (After all, Python rocks! ?)
import re txt = "I Love Java" print("Old String: ", txt) print("New String: ", re.sub('Java', 'Python', txt))
Output:
Old String: I Love Java New String: I Love Python
β‘ So, you can leverage the power of the sub()
method to remove multiple spaces from the given string by simply replacing the extra spaces with a single space.
Example:
# Importing the regular expression library import re # Given string s = "Hello and Welcome to Finxter!" print("String with multiple spaces:") print(s) print("String after removing multiple spaces:") # Replacing the multiple spaces with a single space print(re.sub(' +', ' ', s))
Output:
String with multiple spaces: Hello and Welcome to Finxter! String after removing multiple spaces: Hello and Welcome to Finxter!
Note: Here + within the re.sub()
method represents the occurrence of one or more whitespaces in the given string. Let us have a look at a simple example to understand the working principle of the “+” metacharacter with respect to the regex module.
Example: In the following code we will use the re.findall()
method along with the “+” metacharacter to find all the words in a given string that have the letters “Be” followed by one or more occurrences of the letter “e”.
import re s = "Bear Abcxyz Bee Buebe Beeer Shampoo Beeeen" for i in s.split(" "): if re.findall("Be+e", i): print(i)
Output:
Bee Beeer Beeeen
Do you want to master the regex superpower?
Check out the book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning:
(1) study a book chapter,
(2) solve a code puzzle, and
(3) watch an educational chapter video.
Method 2: Using The split() Method
split()
is a built-in method in Python that is used to cut/split a given string based on a given separator. You can specify any separator according to your requirement, however, by default the separator is whitespace.
Syntax:
- separator is an optional parameter which is used to specify the separator (delimiters). By default it is any whitespace character.
- maxsplit is an optional parameter which allows us to specify the maximum number of splits that we want to perform. By default its value is -1 that is βall occurencesβ.
Solution: In this approach, we call the split()
method that splits the string using whitespaces and then saves the resultant string as a list of words. Then, we will use join()
method to combine the words into a single string and return the output.
# Given string txt = "Hello and Welcome to Finxter!" print("String with multiple spaces:") print(txt) # Removing the multiple spaces using split string print("String after removing multiple spaces:") new_txt = ' '.join(txt.split()) print(new_txt)
Output:
String with multiple spaces: Hello and Welcome to Finxter! String after removing multiple spaces: Hello and Welcome to Finxter!
Recommended Tutorials:
How To Cut A String In Python?
Python String join()
Python String split()
Method 3: Using The replace() Method
This method is one of the simplest methods to remove multiple spaces in a string. Using a while
loop, we will check if there are multiple trailing spaces in the string. If yes, we will replace the multiple spaces with a single space and store it in the original string with the help of the replace()
method. We will keep checking it till the string has no multiple spaces. Finally, we will return the string.
Here’s a complete guide for you to learn about Python’s string replace method: Python String Replace
Now, let us have a look at the following code to understand how we can use the concept mentioned above to solve our problem.
# Given string s = "Hello and Welcome to Finxter!" print("String with multiple spaces:") print(s) # Removing the multiple spaces using while loop if ' ' in s: while ' ' in s: s = s.replace(' ', ' ') print("String after removing multiple spaces:") print(s)
Output:
String with multiple spaces: Hello and Welcome to Finxter! String after removing multiple spaces: Hello and Welcome to Finxter!
Method 4: Using A For Loop
In this method, we use the “for” loop to remove the multiple spaces in a string.
- We will traverse the string using a pointer “
i
” one by one. We will also initialize a variable that will befalse
at the beginning. - For every character in the string, if the character is not space we will directly append it to the new string.
- If the character before the current character was a space, we will update the variable to be
true
. - If the variable
f
becomes true, we will check if it is a comma, question mark, or full stop. If it is, we willpass
else we will append the space.
Letβs look at the code:
Example:
# Given string s = "Hello and Welcome to Finxter!" print("String with multiple spaces:") print(s) # Check if there are spaces f = False # To store the final string with no multiple spaces txt = [] # Removing the multiple spaces using for loop for i in range(len(s)): if s[i] != ' ': # Check if the variable is true if f: if s[i] == '.' or s[i] == ',' or s[i] == '!' or s[i] == '?': pass else: txt.append(' ') f = False # Append the characters with no spaces txt.append(s[i]) # If the previous char was space update the variable as True elif s[i - 1] != ' ': f = True print("String after removing multiple spaces:") print(''.join(txt))
Output:
String with multiple spaces: Hello and Welcome to Finxter! String after removing multiple spaces: Hello and Welcome to Finxter!
Conclusion
Here, we studied different methods that can be used to remove the multiple spaces in a string in Python. I hope that if you had the question – “Is There A Simple Way To Remove Multiple Spaces In A String?“, then this discussion helped you and now you can easily eliminate extra spaces from a string in Python. Stay tuned and subscribe for more interesting discussions in the future.
Post Credits: Shubham Sayon and Rashi Agarwal