Stripping empty spaces in Python
Start your free 7-days trial now!
To strip empty spaces in a string in Python, use the following built-in functions:
Method | Description |
---|---|
Removes all trailing spaces (i.e. spaces on the right). | |
Removes all leading spaces (i.e. spaces on the left). | |
Removes all trailing and leading spaces. | |
Replace all |
Examples
Trailing spaces
To strip all trailing spaces:
x = " Hello World "
' Hello World'
Leading spaces
To strip all leading spaces:
y = " Hello World "
'Hello World '
Trailing and Leading spaces
To strip all trailing and leading spaces:
z = " Hello World "
'Hello World'
Note that in all these examples the original string is left intact and we return a new string with the spaces stripped.
All spaces
To replace all " "
(single space) characters with ""
:
a = " Hello World "
'HelloWorld'
Using this method will only remove the normal ASCII space character and not other whitespace characters such as tabs.
Duplicated spaces
To remove duplicated space characters:
Here we first split the string " Hello World "
into fragments using the space character as a separator. Then we rejoin these fragments using the join method using " " as the separator ensuring we only have single spaces.