Python:在字符串中查找单词

Python:在字符串中查找单词,python,Python,我试图用Python在字符串中查找一个单词 str1 = 'This string' if 'is' in str1: print str1 在上面的例子中,我希望它不打印str1。在下面的示例中,我希望它打印str2 str2 = 'This is a string' if 'is' in str2: print str2 如何在Python中执行此操作?将字符串拆分为单词并进行搜索: if 'is' in str1.split(): # 'is' in ['This',

我试图用Python在字符串中查找一个单词

str1 = 'This string'
if 'is' in str1:
    print str1
在上面的例子中,我希望它不打印str1。在下面的示例中,我希望它打印str2

str2 = 'This is a string'
if 'is' in str2:
    print str2

如何在Python中执行此操作?

将字符串拆分为单词并进行搜索:

if 'is' in str1.split(): # 'is' in ['This', 'string']
    print(str1) # never printed

if 'is' in str2.split(): # 'is' in ['This', 'is', 'a', 'string']
    print(str2) # printed

使用正则表达式的单词边界也有效

import re

if re.findall(r'\bis\b', str1):
    print str1

有一点需要注意:如果不区分大小写,就把句子改成小写fist。谢谢,这就是我要找的。在比较字符串之前,我还使用lower()。