To remove all spaces from a string in Python, the easiest way is with the Python string replace() function.
string = "This is a string with spaces."
print(string.replace(" ",""))
#Output:
Thisisastringwithspaces.
One other easy way to remove all spaces from a string is with regex and the re module.
import re
string = "This is a string with spaces."
print(re.sub('s+',' ',string))
#Output:
Thisisastringwithspaces.
When using string variables in Python, the ability to easily be able to modify and change the value of these variables is important.
One such case is if you want to remove specific characters from a string.
To remove all spaces from a string in Python, the easiest way is with the Python string replace() function.
replace() takes a string to search for and a replacement value and replacing all found strings with the replacement value.
To remove all spaces from a string in Python, you can search for spaces and replace them with an empty string.
Below shows you how to use replace() to remove all spaces in a string in Python.
string = "This is a string with spaces."
print(string.replace(" ",""))
#Output:
Thisisastringwithspaces.
Removing All Spaces from String using Regex with Python
One other way you can remove all spaces from a string is with regex. To perform regex substitution, we can use the Python re module sub() function.
We can easily define a regular expression which will search for any number of spaces, and then using the sub() function, we will replace the spaces with an empty string.
Below are some examples of how you can remove all spaces from strings using Python with the sub() function.
import re
string = "This is a string with spaces."
print(re.sub('s+',' ',string))
#Output:
Thisisastringwithspaces.
Hopefully this article has been useful for you to learn how to remove all spaces from a string in Python.