在列表中搜索单词

时间:2018-12-12 12:39:11

标签: python python-3.x

我要搜索单词hi的存在。

import re
word = 'hi?'

cleanString = re.sub('\W+',' ', word)
print(cleanString.lower())

GREETING_INPUTS = ("hello", 'hi', 'hii', "hey")
if cleanString.lower() in GREETING_INPUTS:
    print('yes')
else:
    print('no')

word = 'hi'时,它打印yes。但是对于word = 'hi?',它会打印no。为什么会这样,请提出任何解决方案。

1 个答案:

答案 0 :(得分:1)

替换此行:

cleanString = re.sub('\W+',' ', word)

使用:

cleanString = re.sub('\W+','', word)

因为要用'\W+'(空格)替换' '的所有匹配项,所以字符串应为'hi ',因此需要用空字符串{{ 1}},字符串将变为''

相关问题