Categories
Python Answers

How to trim string whitespace with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *