How do I trim whitespace from a string?
There are a few ways to trim whitespace from a string in Python.
There are a few ways to trim whitespace from a string in Python.
The easiest way is to use the built-in str.strip() method, which removes all whitespace characters (including spaces, tabs, and newlines) from the beginning and end of a string. For example:
Trim whitespace from a string in Python
Watch a video course: Python - The Practical Guide
You can also use the str.lstrip() method to remove whitespace characters from the left side of a string, and str.rstrip() to remove them from the right side. For example:
Trim whitespace from the left side of a string in Python
You can also use the str.replace() method, but note that it removes all specified characters rather than just trimming leading and trailing whitespace. For example:
Remove all spaces from a string in Python using the replace method
All the above methods work on Python 3 strings.