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 .
  1. str.strip()
  2. str.lstrip()
  3. str.rstrip()
  4. str.replace()
  5. translate()
  6. re.sub()

Python strip() method

If you want to remove leading and ending spaces in a string, use strip():
>>> str = " Python remove whitespace " >>> print(str.strip())
Python remove whitespace

Python lstrip() method

If you want to remove spaces in the beginning of a string , use lstrip():
How to strip all whitespace from string  in python

Python rstrip() method

If you want to remove spaces in the end of a string , use rstrip():
How do I trim whitespace in python

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():
Remove spaces in every where in the string in python

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():
>>> str = " Python translate() method " >>> print(str.translate(str.maketrans('', '', ' \n\t\r')))
Pythontranslate()method
OR if you want to remove only whitespace :
import string >>> str = " Python translate() method " >>> print(str.translate(str.maketrans('', '', string.whitespace)))
Pythontranslate()method

Using Regular Expressions

If you want to remove leading and ending spaces in a string, use strip():
python regular expression
If you want to remove spaces in the beginning of a string , use lstrip():
Regular expression
If you want to remove spaces in the end of a string , use rstrip():
import re str = " Python remove whitespace " str = re.sub(r"\s+$", "", str, flags=re.UNICODE) print(str)
If you want to remove all spaces in a string, even between words:
import re str = " Python remove whitespace " str = re.sub(r"\s+", "", str, flags=re.UNICODE) print(str)

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.
  1. 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.
  2. join(): This method takes all items in the iterable and combines them into a string using a separator.
import re str = " Python remove whitespace " str = " ".join(re.split("\s+", str, flags=re.UNICODE)) print(str)

Or


Remove white spaces from string python