Five Methods of Removing Spaces in Python String
- 2021-10-15 11:01:55
- OfStack
When dealing with Python code strings, we often encounter the situation of removing spaces, so we have summarized various methods for your reference.
1. strip () method
Remove spaces at the beginning or end of a string
str = " Hello world "
str.strip()
Output:
"Hello world"
2. lstrip () method
Remove the space at the beginning of the string
str = " Hello world "
str.lstrip()
Output:
'Hello world '
3. rstrip () method
Remove the space at the end of the string
str = " Hello world "
str.lstrip()
Output:
' Hello world'
4. replace () method
You can remove all spaces
# replace Mainly used for string replacement replace(old, new, count)
str = " Hello world "
str.replace(" ","")
Output:
"Helloworld"
5: join () method + split () method
You can remove all spaces
# join To synthesize incoming characters for character strings 1 A list of strings, 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
>>> "".join(a.split())
'abc'