Python如何检查字符串是否包含单词

时间:2016-01-20 00:54:28

标签: python python-2.7

我正在尝试检查str2中是否存在str1

def string_contains(str1,str2):
    return bool (str1 in str2)

print (string_contains("llo","hello how are you"))
# expected false but return value is true
# the possible true for s1 is hello or hello how or hello how are
# hello how are you

2 个答案:

答案 0 :(得分:1)

这应该有效 - 它将确保只匹配整个单词,并且句子必须从一开始就匹配。

def string_contains(str1,str2):
    lst1 = str1.split(' ')
    lst2 = str2.split(' ')

    if len(lst1) <= len(lst2):
        return lst1 == lst2[:len(lst1)]

    return False

print (string_contains("llo", "hello how are you"))  # False
print (string_contains("hello", "hello how are you"))  # True
print (string_contains("hello how", "hello how are you"))  # True
print (string_contains("hello how a", "hello how are you"))  # False

答案 1 :(得分:0)

我喜欢使用正则表达式模块re

代码:

import re

pattern = re.compile('\sllo\s')  # add another parameter `re.I` for case insensitive
match = pattern.search('hello how are you')
if match:
    return True
else:
    return False