如何从 Python 中的字符串中删除前导空格和尾随空格?
" Hello world " --> "Hello world"
" Hello world" --> "Hello world"
"Hello world " --> "Hello world"
"Hello world" --> "Hello world"
最佳答案
要删除字符串周围的所有空格,请使用 .strip()
.例子:
>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> ' Hello '.strip() # ALL consecutive spaces at both ends removed
'Hello'
请注意 str.strip()
删除所有空白字符,包括制表符和换行符。要仅删除空格,请将要删除的特定字符指定为 strip
的参数:
>>> " Hello\n ".strip(" ")
'Hello\n'
最多只删除一个空格:
def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s
>>> strip_one_space(" Hello ")
' Hello'
关于python - 如何从字符串中修剪空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/761804/