慕田峪7331174
如果您想知道整个单词是否在以空格分隔的单词列表中,只需使用:def contains_word(s, w): return (' ' + w + ' ') in (' ' + s + ' ')contains_word('the quick brown fox', 'brown') # Truecontains_word('the quick brown fox', 'row') # False这种优雅的方法也是最快的。与Hugh Bothwell和daSong的方法相比:>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编辑: Python 3.6+的这个想法略有变化,同样快:def contains_word(s, w): return f' {w} ' in f' {s} '