Python Trim String
- strip(): returns a new string after removing any leading and trailing whitespaces including tabs (t).
- rstrip(): returns a new string with trailing whitespace removed. It’s easier to remember as removing white spaces from “right” side of the string.
- lstrip(): returns a new string with leading whitespace removed, or removing whitespaces from the “left” side of the string.
All of these methods don’t accept any arguments to remove whitespaces. If a character argument is provided, then they will remove that characters from the string from leading and trailing places.
Let’s look at a simple example of trimming whitespaces from the string in Python.
s1 = ' abc '
print(f'String ='{s1}'')
print(f'After Removing Leading Whitespaces String ='{s1.lstrip()}'')
print(f'After Removing Trailing Whitespaces String ='{s1.rstrip()}'')
print(f'After Trimming Whitespaces String ='{s1.strip()}'')
Output:
String =' abc '
After Removing Leading Whitespaces String ='abc '
After Removing Trailing Whitespaces String =' abc'
After Trimming Whitespaces String ='abc'
Let’s look at some more examples with strings having a new-line and tabs.
>>> s1 = ' Xn Y nZ t'
>>> s1.strip()
'Xn Y nZ'
>>> s1.rstrip()
' Xn Y nZ'
>>> s1.lstrip()
'Xn Y nZ t'