我想从字符串的两端以及单词之间消除所有空格。
我有这个 Python 代码:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
但这只会消除字符串两侧的空格。如何删除所有空格?
我想从字符串的两端以及单词之间消除所有空格。
我有这个 Python 代码:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
但这只会消除字符串两侧的空格。如何删除所有空格?
如果要删除前导和结尾空格,请使用str.strip()
:
sentence = ' hello apple'
sentence.strip()
>>> 'hello apple'
如果要删除所有空格字符,请使用str.replace()
:
(注意这只会删除“正常”的 ASCII 空格字符' ' U+0020
,但不会删除任何其他空格)
sentence = ' hello apple'
sentence.replace(" ", "")
>>> 'helloapple'
如果要删除重复的空格,请使用str.split()
:
sentence = ' hello apple'
" ".join(sentence.split())
>>> 'hello apple'
要仅删除空格,请使用str.replace
:
sentence = sentence.replace(' ', '')
要删除所有空白字符(空格、制表符、换行符等),您可以使用split
then join
:
sentence = ''.join(sentence.split())
或正则表达式:
import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)
如果您只想从开头和结尾删除空格,您可以使用strip
:
sentence = sentence.strip()
另一种方法是使用正则表达式并匹配这些奇怪的空白字符。这里有些例子:
删除字符串中的所有空格,甚至在单词之间:
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。所以我们可以使用的一个优雅的单行字符串函数是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)
要从开头和结尾删除空格,请使用strip
.
>> " foo bar ".strip()
"foo bar"
' hello \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})
MaK already pointed out the "translate" method above. And this variation works with Python 3 (see this Q&A).
此外,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'
Python 文档:
import re
sentence = ' hello apple'
re.sub(' ','',sentence) #helloworld (remove all spaces)
re.sub(' ',' ',sentence) #hello world (remove double spaces)
我使用 split() 忽略所有空格并使用 join() 连接字符串。
sentence = ''.join(' hello apple '.split())
print(sentence) #=> 'helloapple'
我更喜欢这种方法,因为它只是一个表达式(不是语句)。
它易于使用,无需绑定到变量即可使用。
print(''.join(' hello apple '.split())) # no need to binding to a variable
在下面的脚本中,我们导入了正则表达式模块,我们用它来用一个空格替换一个或多个空格。这确保了内部多余的空间被删除。然后我们使用 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