Python 5 Common String Spaces Removal Methods

  • 2021-12-12 09:00:55
  • OfStack

Catalog 1: strip () Method 2: lstrip () Method 3: rstrip () Method 4: replace () Method 5: join () Method + split () Method

1: strip () method

Remove spaces at the beginning or end of a string


>>> a = " a b c "

>>> a.strip()

'a b c'

2: lstrip () method

Remove the space at the beginning of the string


>>> a = " a b c "

>>> a.lstrip()

'a b c '

3: rstrip () method

Remove the space at the end of the string


'''
 No one answers the problems encountered in study? Xiaobian created 1 A Python Learning and communication group: 531509025
 Looking for like-minded friends and helping each other , There are also good video learning tutorials and PDF E-books! 
'''
>>> a = " a b c "

>>> a.rstrip()

' a b c'

4: replace () method

You can remove all spaces

replace Mainly used for string replacement replace(old, new, count)


>>> a = " a b c "

>>> a.replace(" ", "")

'abc'

5: join () method + split () method

You can remove all spaces

join Pass in 1 string list for character string composition, split For string segmentation, it can be segmented according to rules


>>> a = " a b c "

>>> b = a.split()  #  The string is divided into a list by space 

>>> b ['a', 'b', 'c']

>>> c = "".join(b) #  Use 1 Three empty strings synthesize the contents of the list to generate a new string 

>>> c 'abc'
 
#  Quick usage 

>>> a = " a b c "

>>> "".join(a.split())

'abc'

Related articles: