Stripping empty spaces in Python
To strip empty spaces in a string in Python, use the following built-in functions:
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.
To strip all trailing spaces:
x = " Hello World "x.rstrip()' Hello World'
To strip all leading spaces:
y = " Hello World "y.lstrip()'Hello World '
Trailing and Leading spaces
To strip all trailing and leading spaces:
z = " Hello World "z.strip()'Hello World'
Note that in all these examples the original string is left intact and we return a new string with the spaces stripped.
To replace all
" " (single space) characters with
a = " Hello World "a.replace(" ", "")'HelloWorld'
Using this method will only remove the normal ASCII space character and not other whitespace characters such as tabs.
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.