Python – 检查字是否在string中

我正在使用Python v2,我试图找出是否可以告诉一个字是否在string中。

我已经find了一些关于识别string是否在string中的信息 – 使用.find,但有没有办法做一个IF语句。 我想有以下的东西:

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

谢谢你的帮助。

出什么问题了:

 if word in mystring: print 'success' 
 if 'seek' in 'those who seek shall find': print('Success!') 

但请记住,这与一系列字符相匹配,而不一定是一个完整的单词 – 例如, 'word' in 'swordsmith'为真。 如果你只想匹配整个单词,你应该使用正则expression式:

 import re def findWholeWord(w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search findWholeWord('seek')('those who seek shall find') # -> <match object> findWholeWord('word')('swordsmith') # -> None 

find返回一个表示search项目被find的索引的整数。 如果找不到,则返回-1。

 haystack = 'asdf' haystack.find('a') # result: 0 haystack.find('s') # result: 1 haystack.find('g') # result: -1 if haystack.find(needle) >= 0: print 'Needle found.' else: print 'Needle not found.' 

如果你想知道一个单词是否在空格分隔的单词列表中,只需使用:

 def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ') contains_word('the quick brown fox', 'brown') # True contains_word('the quick brown fox', 'row') # False 

这个优雅的方法也是最快的。 与休·博思韦尔和达松的方法相比:

 >python -m timeit -s "def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ')" "contains_word('the quick brown fox', 'brown')" 1000000 loops, best of 3: 0.351 usec per loop >python -m timeit -s "import re" -s "def contains_word(s, w): return re.compile(r'\b({0})\b'.format(w), flags=re.IGNORECASE).search(s)" "contains_word('the quick brown fox', 'brown')" 100000 loops, best of 3: 2.38 usec per loop >python -m timeit -s "def contains_word(s, w): return s.startswith(w + ' ') or s.endswith(' ' + w) or s.find(' ' + w + ' ') != -1" "contains_word('the quick brown fox', 'brown')" 1000000 loops, best of 3: 1.13 usec per loop 

这个小函数比较给定文本中的所有search词。 如果在文本中find所有search词,则返回search长度,否则返回False

还支持Unicodestringsearch。

 def find_words(text, search): """Find exact words""" dText = text.split() dSearch = search.split() found_word = 0 for text_word in dText: for search_word in dSearch: if search_word == text_word: found_word += 1 if found_word == len(dSearch): return lenSearch else: return False 

用法:

 find_words('çelik güray ankara', 'güray ankara') 

如果匹配一个字符序列是不够的,你需要匹配整个单词,这是一个简单的function,完成工作。 它基本上在需要的地方追加空格,然后在string中search:

 def smart_find(haystack, needle): if haystack.startswith(needle+" "): return True if haystack.endswith(" "+needle): return True if haystack.find(" "+needle+" ") != -1: return True return False 

这假定逗号和其他标点已被删除。

您可以将string拆分为单词并检查结果列表。

 if word in string.split(): print 'success' 

先进的方式来检查确切的单词,我们需要find一个长串:

 import re text = "This text was of edited by Rock" #try this string also #text = "This text was officially edited by Rock" for m in re.finditer(r"\bof\b", text): if m.group(0): print "Present" else: print "Absent" 

你可以在“单词”之前和之后添加一个空格。

 x = raw_input("Type your word: ") if " word " in x: print "Yes" elif " word " not in x: print "Nope" 

这样它就会查找“word”前后的空格。

 >>> Type your word: Swordsmith >>> Nope >>> Type your word: word >>> Yes 

当你要求一个字,而不是一个string,我想提出一个解决scheme,不敏感的前缀/后缀,并忽略大小写:

 #!/usr/bin/env python import re def is_word_in_text(word, text): """ Check if a word is in a text. Parameters ---------- word : str text : str Returns ------- bool : True if word is in text, otherwise False. Examples -------- >>> is_word_in_text("Python", "python is awesome.") True >>> is_word_in_text("Python", "camelCase is pythonic.") False >>> is_word_in_text("Python", "At the end is Python") True """ pattern = r'(^|[^\w]){}([^\w]|$)'.format(word) pattern = re.compile(pattern, re.IGNORECASE) matches = re.search(pattern, text) return bool(matches) if __name__ == '__main__': import doctest doctest.testmod() 

如果你的话可能包含正则expression式的特殊字符(如+ ),那么你需要re.escape(word)