Python-检查字符串中的多个空格 [英] Python - Check multiple white spaces in string
问题描述
我正在使用此功能来检查一个字符串是否包含多个空格:
I am using this function to check if a string contains multiple white spaces:
def check_multiple_white_spaces(text):
return " " in text
,它通常可以正常工作,但不能在以下代码中进行操作:
and it is usually working fine, but not in this following code:
from bs4 import BeautifulSoup
from string import punctuation
text = "<p>Hello world!!</p>\r\n\r"
text = BeautifulSoup(text, 'html.parser').text
text = ''.join(ch for ch in text if ch not in set(punctuation))
text = text.lower().replace('\n', ' ').replace('\t', '').replace('\r', '')
print check_multiple_white_spaces(text)
text
变量的最终值是hello world
,但是我不知道为什么check_multiple_white_spaces
函数返回False
而不是True
.
The final value of text
variable is hello world
, but I don't know why the check_multiple_white_spaces
function is returning False
instead of True
.
我该如何解决?
推荐答案
如果要使用repr()
打印text
的内容,您将看到它不包含两个连续的空格:
If you were to print the contents of text
using repr()
, you will see that it does not contain two consecutive spaces:
'hello \xa0 \xa0 \xa0world '
因此,您的函数正确返回了False
.可以通过将不间断空格转换为空格来解决此问题:
As a result, your function correctly returns False
. This could be fixed by converting the non-break space into a space:
text = text.replace(u'\xa0', u' ')
这篇关于Python-检查字符串中的多个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!