我想使用python在字符串中查找多个空格。如何检查字符串中是否存在多个空格?
mystring = 'this is a test'
我尝试过下面的代码,但它不起作用。
if bool(re.search(' +', ' ', mystring))==True:
# ....
结果必须返回True
。
您可以使用split()
,如果您不指定分隔符,它会将空格视为分隔符。拆分后检查长度。如果长度大于1,则它有空格。
mystring = 'this is a test'
if len(mystring.split()) > 1:
#do something
您可以使用string.count((方法:如果你想检查是否存在多个(不止一个,无论它们的长度如何(空间,代码是:
mystring.count(' ')>1
如果你想检查是否至少有一个连续的空格,代码是:
mystring.count(' ')>=1
您可以使用re来比较字符串,如下所示:
import re
mystring = 'this is a test'
new_str = re.sub(' +', ' ', mystring)
if mystring == new_str:
print('There are no multiple spaces')
else:
print('There are multiple spaces')
用于re.search
的语法错误。它应该是re.search(pattern, string, flags=0)
。
所以,你可以做,搜索2个或更多的空间:
import re
def contains_multiple_spaces(s):
return bool(re.search(r' {2,}', s))
contains_multiple_spaces('no multiple spaces')
# False
contains_multiple_spaces('here are multiple spaces')
# True