Net-informations.com

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():

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():

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():


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():

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.

  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.

Or


Remove white spaces from string python









net-informations.com (C) 2021    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About