我想消除字符串的所有空白,在两端和单词之间。
我有这样的Python代码:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
但这只是消除了字符串两侧的空白。如何删除所有空白?
我想消除字符串的所有空白,在两端和单词之间。
我有这样的Python代码:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
但这只是消除了字符串两侧的空白。如何删除所有空白?
当前回答
我使用split()忽略所有空白,使用join()连接 字符串。
sentence = ''.join(' hello apple '.split())
print(sentence) #=> 'helloapple'
我更喜欢这种方法,因为它只是一个表达式(不是一个语句)。 它易于使用,并且无需绑定到变量即可使用。
print(''.join(' hello apple '.split())) # no need to binding to a variable
其他回答
消除字符串两端和单词之间的所有空白。
>>> import re
>>> re.sub("\s+", # one or more repetition of whitespace
'', # replace with empty string (->remove)
''' hello
... apple
... ''')
'helloapple'
https://en.wikipedia.org/wiki/Whitespace_character
Python文档:
https://docs.python.org/library/stdtypes.html#textseq https://docs.python.org/library/stdtypes.html#str.replace https://docs.python.org/library/string.html#string.replace https://docs.python.org/library/re.html#re.sub https://docs.python.org/library/re.html#regular-expression-syntax
在下面的脚本中,我们导入正则表达式模块,用于用一个空格替换一个或多个空格。这确保了内部多余的空间被删除。然后使用strip()函数删除前导和尾随空格。
# Import regular expression module
import re
# Initialize string
a = " foo bar "
# First replace any number of spaces with a single space
a = re.sub(' +', ' ', a)
# Then strip any leading and trailing spaces.
a = a.strip()
# Show results
print(a)
如果要删除开头和结尾的空白,请使用strip。
>> " foo bar ".strip()
"foo bar"
如果你想删除开头和结尾空格,使用str.strip():
>>> " hello apple ".strip()
'hello apple'
如果你想删除所有空格字符,使用str.replace()(注意,这只删除“正常的”ASCII空格字符' ' U+0020,而不删除任何其他空白字符):
>>> " hello apple ".replace(" ", "")
'helloapple'
如果你想删除重复的空格,使用str.split()后面跟着str.join():
>>> " ".join(" hello apple ".split())
'hello apple'
此外,strip还有一些变化:
删除字符串开头和结尾的空格:
sentence= sentence.strip()
删除字符串开头的空格:
sentence = sentence.lstrip()
删除字符串END中的空格:
sentence= sentence.rstrip()
这三个字符串函数都可以对lstrip和rstrip进行strip,默认为全空白。当你处理一些特殊的东西时,这是很有用的,例如,你可以只删除空格而不删除换行:
" 1. Step 1\n".strip(" ")
或者你可以在读入字符串列表时删除额外的逗号:
"1,2,3,".strip(",")