Python-检查Word是否在字符串中


175

我正在使用Python v2,并且正在尝试找出是否可以判断字符串中是否包含单词。

我发现了一些有关识别单词是否在字符串中的信息-使用.find,但是有一种方法可以执行IF语句。我想要以下内容:

if string.find(word):
    print 'success'

谢谢你的帮助。

Answers:


348

出什么问题了:

if word in mystring: 
   print 'success'

103
谨慎起见,如果您有一个字符串“ paratyphoid is bad”,而如果您在“ paratyphoid is bad”中执行了if“ typhoid”,您将得到一个真实的结果。
戴维·尼尔森

3
有谁知道如何克服这个问题?
user2567857

4
@ user2567857,正则表达式-请参见休·博特威尔的答案。
Mark Rajcok

4
if(mystring中的word1和mystring中的word2)
louie mcconnell '16

2
这是如何被接受的答案?!它只是检查字符串中是否包含字符序列(不是单词)
pedram bashiri 19-11-19
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.