Strip trailing whitespaces from string [Python]

If you want to remove extra whitespaces from start and end of a string, use strip() method in Python. strip() method removes all default whitespaces (spaces and tabs \t) and returns the copy of the string.

Python code to strip trailing whitespaces from string

string = "  xyz is equal to xyz  " # string with whitespaces (spaces and tabs)
print "string with trailing whitespaces is \"" + string + "\"" # printing string with trailing whitespaces
string = string.strip() # strip trailing whitespaces
print "string after stripping trailing whitespaces is \"" + string + "\""  # printing the string after stripping trailing whitespaces

Note: Code works in both Python 2 and 3

Output on Windows PowerShell

strip-trailing-white-spaces-Python-code

Read -> Find the Position of next occurrence of a sub-string in python

About the Author

SRINI S

A passionate blogger. Love to share solutions and best practices on wordpress hosting, issues and fixes, excel VBA macros and other apps

Leave a Reply

Your email address will not be published. Required fields are marked *