When working with Python strings, a pretty common question is how to trim whitespace from a string. Whitespace characters are the space (
\t), newline (
\n), and carriage return characters (
\r). Here are 3 different methods to trim whitespace from a string in Python.
str.strip() method to remove whitespace characters from both the beginning and end of a string.
' Hello '.strip() # 'Hello'
Leading whitespace characters are the whitespace characters at the start of a string. To remove them, use the
' Hello '.lstrip() # 'Hello '
Trailing whitespace characters are the whitespace characters at the end of a string. To remove them, use the
' Hello '.rstrip() # ' Hello'
Learn of the two different way to convert a string to lowercase in Python and understand when you should use each one with this quick guide.
Pads a string on both sides with the specified character, if it's shorter than the specified length.
Python's f-strings can do a lot more than you might expect. Learn a few useful tips and tricks in this quick guide.