How to remove whitespace from a string in python
In Python, there are various approaches to remove whitespaces in a string. By using the following methods, let's see how to remove whitespaces in a string .
- str.strip()
- str.lstrip()
- str.rstrip()
- str.replace()
- translate()
- re.sub()
Python strip() method
If you want to remove leading and ending spaces in a string, use strip():
Python lstrip() method
If you want to remove spaces in the beginning of a string , use lstrip():

Python rstrip() method
If you want to remove spaces in the end of a string , use rstrip():

All three string functions strip lstrip, and rstrip can take parameters of the string to strip, with the default being all white space.
Python replace() method
If you want to remove all space characters , use replace():

Python translate() method
If you want to remove all Whitespaces includes space, tabs, and CRLF. So an elegant and one-liner string function you can use is translate():
OR if you want to remove only whitespace :
Using Regular Expressions
If you want to remove leading and ending spaces in a string, use strip():

If you want to remove spaces in the beginning of a string , use lstrip():

If you want to remove spaces in the end of a string , use rstrip():
If you want to remove all spaces in a string, even between words:
Remove all duplicate whitespaces in the string
If you want to remove all the duplicate whitespaces and newline characters, then you can use join() function with string split() function.
- split(): Returns list of all words in the string separated using delimiter string. If the delimiter is not mentioned, by default whitespace is the delimiter.
- join(): This method takes all items in the iterable and combines them into a string using a separator.
Or
