我想消除字符串的所有空白,在两端和单词之间。
我有这样的Python代码:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
但这只是消除了字符串两侧的空白。如何删除所有空白?
我想消除字符串的所有空白,在两端和单词之间。
我有这样的Python代码:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
但这只是消除了字符串两侧的空白。如何删除所有空白?
当前回答
试试这个. .比起使用re,我认为使用split和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
其他回答
如果只删除空格,请使用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()
还可以使用lstrip删除字符串开头的空白,使用rstrip删除字符串末尾的空白。
另一种方法是使用正则表达式并匹配这些奇怪的空白字符。下面是一些例子:
删除字符串中的所有空格,甚至在单词之间:
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)
删除字符串的begin和END中的空格:
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中都可以工作)
' hello \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})
MaK已经在上面指出了“翻译”方法。这种变化适用于Python 3(请参阅此问答)。
在下面的脚本中,我们导入正则表达式模块,用于用一个空格替换一个或多个空格。这确保了内部多余的空间被删除。然后使用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"