Sometimes, we want to trim string whitespace with Python.
In this article, we’ll look at how to trim string whitespace with Python.
How to trim string whitespace with Python?
To trim string whitespace with Python, we can use the string’s strip
method to trim leading and trailing whitespace.
rstrip
strips trailing whitespace only.
And lstrip
strips leading whitespace only.
For instance, we write:
s = " \t a string example\t "
s1 = s.strip()
s2 = s.rstrip()
s3 = s.lstrip()
print(s1)
print(s2)
print(s3)
We call strip
, rstrip
and lstrip
on s
to strip leading and trailing whitespaces, trailing whitespaces, and leading whitespaces respectively.
And then we assign the returned string to s1
, s2
and s3
.
Therefore, we get:
a string example
a string example
a string example
from the print
output.
Conclusion
To trim string whitespace with Python, we can use the string’s strip
method to trim leading and trailing whitespace.
rstrip
strips trailing whitespace only.
And lstrip
strips leading whitespace only.