Python five common methods of string space removal

Time:2022-5-21
catalogue
  • 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 the string

?
1
2
3
4
5
>>> a = " a b c "
 
>>> a.strip()
 
'a b c'

2: Lstrip() method

Remove spaces at the beginning of the string

?
1
2
3
4
5
>>> a = " a b c "
 
>>> a.lstrip()
 
'a b c '

3: Rstrip() method

Remove spaces at the end of the string

?
1
2
3
4
5
6
7
8
9
'''
No one answers the problems encountered in learning? Xiaobian created a python learning exchange group: 531509025
Look for like-minded friends to help each other. There are also good video learning tutorials and PDF e-books in the group!
'''
>>> a = " a b c "
 
>>> a.rstrip()
 
' a b c'

4: Replace() method

All spaces can be removed

replaceIt is mainly used for string replacementreplace(old, new, count)

?
1
2
3
4
5
>>> a = " a b c "
 
>>> a.replace(" ", "")
 
'abc'

5: Join() method + split() method

All spaces can be removed

joinThe incoming string is synthesized into a string,splitUsed for string segmentation, which can be divided according to rules

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> a = " a b c "
 
>>> b = a.split()  #Strings are separated into lists by spaces
 
>>> b ['a', 'b', 'c']
 
>>> c = "".join(b) #Use an empty string to synthesize the contents of the list to generate a new string
 
>>> c 'abc'
 
#Quick usage
 
>>> a = " a b c "
 
>>> "".join(a.split())
 
'abc'

This is the end of this article on the five common methods of string space removal in Python. For more information about the methods of string space removal in Python, please search the previous articles of developeppaper or continue to browse the relevant articles below. I hope you will support developeppaper more in the future!