Python-Common ways to remove spaces from strings

Python provides a method to remove spaces from strings, which can meet most needs.
However, in practical applications, it is necessary to flexibly use other Python methods to delete string spaces.
For example, removing all spaces in a string, retaining one consecutive space in a string, etc., all need to be implemented in combination with other methods.
The following is a brief summary of three application scenarios and corresponding processing methods for removing string spaces, for reference.

1. Python comes with a method for removing spaces

Python comes with some methods for removing spaces from strings, which can meet some needs. The methods and explanations are as follows:

method Definition
str.strip() Remove spaces from the beginning or end of a string.
str.lstrip() Remove spaces from the beginning of the string.
str.rstrip() Remove spaces from the end of a string.

Example: How to handle spaces in strings in the table above

# 字符串空格处理
a_str = ' 甲之蜜糖,   乙之砒霜 '
print('开头或结尾空格:', a_str.strip())
print('去掉开头的空格:', a_str.lstrip())
print('去掉结尾的空格:', a_str.rstrip())

Insert image description here

2. Use other methods to remove all spaces

Python comes with the most commonly used method for removing spaces from a string, but if you want to remove all spaces in a string, you need to use other methods.
The following is how to remove all spaces in a string.

(1) replace() method

replace() method, syntax: str.replace(old,new[,max])
old: the substring to be replaced
new: new string, used to replace the old substring
max: optional parameter, the maximum replacement Times
Example: Remove all spaces from string

a_str = ' 甲之蜜糖,   乙之砒霜 '
b_str = a_str.replace(' ', '')
print('去掉字符串所有空格:', b_str)

Insert image description here

(2) join()+split() method

Use the join() and split() methods in python to remove all spaces in the original string.
Usage is as follows:

a_str = ' 甲之蜜糖,   乙之砒霜 '
b_str = ''.join(a_str.split())
print('去掉字符串所有空格:', b_str)

Insert image description here
Note : The str.split(sep[,num]) method, when the separator (sep) is not specified, defaults to all empty characters, including spaces, newlines (\n), tabs (\t), etc. But it cannot be empty (''), such as str.split('') is illegal.
The incorrect usage is as follows:

a_str = ' 甲之蜜糖,   乙之砒霜 '
print(a_str.split(''))

Insert image description here

3. Keep one space for multiple consecutive spaces.

Sometimes, it is necessary to remove excess spaces in a string and retain one of multiple consecutive spaces. In this case, the join()+split() method is used.
The specific usage is as follows:

a_str = ' 甲之蜜糖,   乙之砒霜 '
b_str = ' '.join(a_str.split())
print('连续空格保留一个:', b_str)

Insert image description here

The above are common methods and application scenarios for removing spaces from strings.

-end-

Guess you like

Origin blog.csdn.net/LHJCSDNYL/article/details/132996085