Python – How to trim a String?

In Python trim method is called strip, it removes the leading and trailing spaces of a String.


str.strip()  #trim
str.lstrip() #ltrim
str.rstrip() #rtrim

#!/usr/bin/python
str = "   abc   "

print(str)
print(str.strip())
print(str.lstrip())
print(str.rstrip())

Output


{space} abc {space}
abc
abc {space}
{space} abc

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar