How to Trim Space from a String in Python

Python provides three methods that can be used to trim whitespaces from the string object. In Python, you can use the .strip() method to remove whitespace characters from the beginning and end of a string. If you want to remove specific characters from the beginning and end of a string, you can use the .lstrip() and .rstrip() methods and pass in the characters you want to remove as an argument.

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.

aStr = ' Minhaj '
print(f'String Before Removing Whitespace =\'{aStr}\'')
print(f'After Removing Leading Whitespaces String =\'{aStr.lstrip()}\'')
print(f'After Removing Trailing Whitespaces String =\'{aStr.rstrip()}\'')
print(f'After Trimming Whitespaces String =\'{aStr.strip()}\'')

Output:

String Before Removing Whitespace ='  Minhaj  '
After Removing Leading Whitespaces String ='Minhaj  '
After Removing Trailing Whitespaces String ='  Minhaj'
After Trimming Whitespaces String ='Minhaj'

In this tutorial, I tried to brief how to trim space from a string in Python . Hope you have enjoyed the tutorial. If you want to get updated, like my facebook page https://www.facebook.com/LearningBigDataAnalytics and stay connected.

Add a Comment