我想消除字符串两端和单词之间的所有空白。
我有这个Python代码:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
但是那只会消除字符串两侧的空白。如何删除所有空格?
如果要删除开头和结尾的空格,请使用str.strip()
:
str.strip()
如果要删除所有空格,请使用sentence = ' hello apple'
sentence.strip()
>>> 'hello apple'
:
str.replace()
如果要删除重复的空格,请使用str.replace()
:
sentence = ' hello apple'
sentence.replace(" ", "")
>>> 'helloapple'
要删除仅空格,请使用str.split()
:
str.split()
要删除所有空白字符(空格,制表符,换行符等),可以先使用sentence = ' hello apple'
" ".join(sentence.split())
>>> 'hello apple'
,然后使用str.replace
:
str.replace
或正则表达式:
sentence = sentence.replace(' ', '')
如果只想从开头和结尾删除空格,则可以使用split
:
split
您还可以使用join
仅从字符串的开头删除空格,并使用join
从字符串的结尾删除空格。
要从开头和结尾删除空格,请使用these strange white-space characters。
import re
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)
import re
sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)
MaK已经指出了上面的“翻译”方法。并且此变体适用于Python 3(请参见import re
sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)
)。
请注意:
[import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)
执行rstrip和lstrip(删除前导和尾随空格,制表符,返回和换页,但不会在字符串中间删除它们)。
如果仅替换空格和制表符,则可能会得到隐藏的CRLF,这些CRLF看起来与您要查找的内容相匹配,但并不相同。
import re
sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))
此外,str.translate
有一些变化:
删除字符串的开头和结尾的空格:
str.translate
在字符串的开头删除空格:
' hello apple'.translate(None, ' \n\t\r')
删除字符串末尾的空格:
import string
' hello apple'.translate(None, string.whitespace)
所有三个字符串函数strip
>> " foo bar ".strip()
"foo bar"
和' hello \n\tapple'.translate( { ord(c):None for c in ' \n\t\r' } )
都可以采用要剥离的字符串的参数,默认为全空格。当您处理某些特殊内容时,这可能会很有帮助,例如,您只能删除空格,而不能删除换行符:
this Q&A
或者您可以在读取字符串列表时删除多余的逗号:
strip