我正在使用Python,我试图找出你是否可以判断一个单词是否在字符串中。
我找到了一些关于识别单词是否在字符串中的信息-使用.find,但是否有一种方法来执行if语句。我想要这样的东西:
if string.find(word):
print("success")
我正在使用Python,我试图找出你是否可以判断一个单词是否在字符串中。
我找到了一些关于识别单词是否在字符串中的信息-使用.find,但是否有一种方法来执行if语句。我想要这样的东西:
if string.find(word):
print("success")
当前回答
你可以在"word"前后加一个空格。
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
其他回答
出了什么问题:
if word in mystring:
print('success')
如果你想知道一个完整的单词是否在一个以空格分隔的单词列表中,只需使用:
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
这种优雅的方法也是最快的。与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} '
你可以在"word"前后加一个空格。
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
您可以将字符串拆分为单词并检查结果列表。
if word in string.split():
print("success")
解决方案之一是在测试单词的开头和结尾放置一个空格。如果单词位于句首或句尾,或在任何标点符号旁边,则不适用。我的解决方案是编写一个函数,用空格替换测试字符串中的任何标点符号,并在开头和结尾或测试字符串和测试单词之间添加一个空格,然后返回出现的次数。这是一个简单的解决方案,不需要任何复杂的正则表达式。
def countWords(word, sentence):
testWord = ' ' + word.lower() + ' '
testSentence = ' '
for char in sentence:
if char.isalpha():
testSentence = testSentence + char.lower()
else:
testSentence = testSentence + ' '
testSentence = testSentence + ' '
return testSentence.count(testWord)
计算一个单词在字符串中出现的次数:
sentence = "A Frenchman ate an apple"
print(countWords('a', sentence))
返回1
sentence = "Is Oporto a 'port' in Portugal?"
print(countWords('port', sentence))
返回1
使用'if'中的函数来测试单词是否存在于字符串中