Is there a Python function that will trim whitespace (spaces and tabs) from a string?
(是否有Python函数可以从字符串中修剪空白(空格和制表符)?)
Example: \t example string\t
→ example string
(示例: \t example string\t
→ example string
)
Is there a Python function that will trim whitespace (spaces and tabs) from a string?
(是否有Python函数可以从字符串中修剪空白(空格和制表符)?)
Example: \t example string\t
→ example string
(示例: \t example string\t
→ example string
)
Whitespace on both sides:
(两侧的空格:)
s = " a string example "
s = s.strip()
Whitespace on the right side:
(右侧的空格:)
s = s.rstrip()
Whitespace on the left side:
(左侧的空白:)
s = s.lstrip()
As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:
(正如thedz所指出的,您可以提供一个参数来将任意字符剥离到以下任何函数中,如下所示:)
s = s.strip('
')
This will strip any space, \t
, \n
, or \r
characters from the left-hand side, right-hand side, or both sides of the string.
(这将从字符串的左侧,右侧或两侧去除所有空格, \t
, \n
或\r
字符。)
The examples above only remove strings from the left-hand and right-hand sides of strings.
(上面的示例仅从字符串的左侧和右侧删除字符串。)
If you want to also remove characters from the middle of a string, tryre.sub
: (如果您还想从字符串中间删除字符,请尝试re.sub
:)
import re
print re.sub('[s+]', '', s)
That should print out:
(那应该打印出来:)
astringexample