Sometimes, we want to trim whitespace with Python.
In this article, we’ll look at how to trim whitespace with Python.
How to trim whitespace with Python?
To trim whitespace with Python, we can use the strip
, rstrip
or lstrip
methods.
For instance, we write
s = " \t a string example\t "
s = s.strip()
to return a string with the whitespaces at the start and the end of string s
stripped out.
If we just want to trim the whitespaces at the end of a string, we write
s = s.rstrip()
And if we just want to trim the whitespaces at the start of a string, we write
s = s.lstrip()
Conclusion
To trim whitespace with Python, we can use the strip
, rstrip
or lstrip
methods.