Last Updated: 5 Sep, 2024. In Python, handling strings is a fundamental skill. Fortunately there are several built-in methods for this. Here you can see practical examples and best practices for removing spaces from strings in Python.
Space or whitespace?
A space and a whitespace is actually not the same thing. A space is what you get when you press the spacebar. It’s a specific character (Unicode U+0020) that is used to separate words.
A whitespace is either a space, a tab, a newline or any other character that produces an area without text. Some python methods only removes spaces, others remove all kinds of whitespaces.
Remove whitespaces to the left and right of your sentence
Method: strip()
text = " Hello my friend. "
myNewText = text.strip()
print(myNewText)
Output:
"Hello my friend."
Remove whitespaces to the left of your sentence
Method: lstrip()
text = " Hello my friend. "
myNewText = text.lstrip()
print(myNewText)
Output:
"Hello my friend. "
Remove whitespaces to the right of your sentence
Method: rstrip()
text = " Hello my friend. "
myNewText = text.rstrip()
print(myNewText)
Output:
" Hello my friend."
Remove all whitespaces from your string
Method: split() and join()
text = " Hello my friend."
myNewText = ''.join(text.split())
print(myNewText)
Output:
"Hellomyfriend."