Python provides three methods that can be used to trim whitespaces from the string object.
Python Trim 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 = ' X\n Y \nZ \t' >>> s1.strip() 'X\n Y \nZ' >>> s1.rstrip() ' X\n Y \nZ' >>> s1.lstrip() 'X\n Y \nZ \t'
You can checkout more Python string examples from our
GitHub Repository
.
GitHub Repository
.