Python-检查字符串中的多个空格 [英] Python - Check multiple white spaces in string

查看:868
本文介绍了Python-检查字符串中的多个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此功能来检查一个字符串是否包含多个空格:

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 &nbsp; &nbsp; &nbsp;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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆