我想从字符串的两端以及单词之间消除所有空格。
我有这个 Python 代码:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
但这只会消除字符串两侧的空格。如何删除所有空格?
hello apple
? helloapple
?
如果要删除前导和结尾空格,请使用 str.strip()
:
>>> " hello apple ".strip()
'hello apple'
如果要删除所有空格字符,请使用 str.replace()
(注意,这只会删除“正常”的 ASCII 空格字符 ' ' U+0020
而不是 any other whitespace):
>>> " hello apple ".replace(" ", "")
'helloapple'
如果要删除重复的空格,请使用 str.split()
,后跟 str.join()
:
>>> " ".join(" hello apple ".split())
'hello apple'
要删除仅空格,请使用 str.replace
:
sentence = sentence.replace(' ', '')
要删除所有空白字符(空格、制表符、换行符等),您可以使用 split
,然后使用 join
:
sentence = ''.join(sentence.split())
或正则表达式:
import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)
如果您只想从开头和结尾删除空格,您可以使用 strip
:
sentence = sentence.strip()
您还可以使用 lstrip
仅删除字符串开头的空格,使用 rstrip
删除字符串末尾的空格。
yourstr.translate(str.maketrans('', '', ' \n\t\r'))
另一种方法是使用正则表达式并匹配 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)
删除字符串 END 中的空格:
import re
sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)
删除字符串开头和结尾的空格:
import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)
仅删除重复的空格:
import re
sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))
(所有示例都适用于 Python 2 和 Python 3)
“空白”包括空格、制表符和 CRLF。因此,我们可以使用的优雅的 one-liner 字符串函数是 str.translate
:
蟒蛇 3
' hello apple '.translate(str.maketrans('', '', ' \n\t\r'))
或者,如果您想彻底:
import string
' hello apple'.translate(str.maketrans('', '', string.whitespace))
蟒蛇2
' hello apple'.translate(None, ' \n\t\r')
或者,如果您想彻底:
import string
' hello apple'.translate(None, string.whitespace)
\xc2\xa0
这样的 Unicode 空格没有帮助
ans.translate( None, string.whitespace )
只为我生成 builtins.TypeError: translate() takes exactly one argument (2 given)
。文档说这个参数是一个翻译表,见 string.maketrans()。但请参阅下面 Amnon Harel 的评论。
' hello apple'.translate(str.maketrans('', '', string.whitespace))
注意:如果您打算多次执行此操作,最好创建一个变量来存储转换表。
要从开头和结尾删除空格,请使用 strip
。
>> " foo bar ".strip()
"foo bar"
' hello \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})
MaK 已经指出了上面的“翻译”方法。此变体适用于 Python 3(请参阅 this Q&A)。
xxx.translate( { ord(c) :None for c in string.whitespace } )
表示彻底。
此外,strip 有一些变体:
删除字符串开头和结尾的空格:
sentence= sentence.strip()
删除字符串开头的空格:
sentence = sentence.lstrip()
删除字符串 END 中的空格:
sentence= sentence.rstrip()
所有三个字符串函数 strip
lstrip
和 rstrip
都可以获取字符串的参数以进行剥离,默认为全空格。这在您处理特定内容时会很有帮助,例如,您可以只删除空格但不能删除换行符:
" 1. Step 1\n".strip(" ")
或者您可以在读取字符串列表时删除多余的逗号:
"1,2,3,".strip(",")
当心:
strip
执行 rstrip 和 lstrip(删除前导和尾随空格、制表符、回车和换页符,但不会在字符串中间删除它们)。
如果您只替换空格和制表符,您最终可能会得到隐藏的 CRLF,这些 CRLF 看起来与您要查找的内容相匹配,但并不相同。
消除字符串中、两端和单词之间的所有空格。
>>> 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
re
,但我发现问题标题的实际答案有点隐藏在所有其他选项中。
我使用 split() 忽略所有空格并使用 join() 连接字符串。
sentence = ''.join(' hello apple '.split())
print(sentence) #=> 'helloapple'
我更喜欢这种方法,因为它只是一个表达式(不是语句)。它易于使用,无需绑定到变量即可使用。
print(''.join(' hello apple '.split())) # no need to binding to a variable
import re
sentence = ' hello apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub(' ',' ',sentence) #hello world (remove double spaces)
在下面的脚本中,我们导入了正则表达式模块,我们用它来用一个空格替换一个或多个空格。这确保了内部多余的空间被删除。然后我们使用 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)
试试这个..而不是使用 re 我认为使用 split with strip 更好
def my_handle(self):
sentence = ' hello apple '
' '.join(x.strip() for x in sentence.split())
#hello apple
''.join(x.strip() for x in sentence.split())
#helloapple
不定期副业成功案例分享
sentence.join(str_list)
时,您要求 python 以sentence
作为分隔符加入 str_list 中的项目。"".join(sentence.split())
确实是规范的解决方案,有效地删除 all 空格而不仅仅是空格。 Mark Byers' excellent answer 可能应该被接受来代替这个不太适用的答案。