如何在python中检查字符串中的精确单词

use*_*103 11 python string

基本上我需要找到一种方法来找出一种在字符串中找到精确单词的方法.我在网上阅读的所有信息都只给了我如何搜索字符串中的字母

98787这是对的

仍然会在if语句中回归.

这就是我到目前为止所拥有的.

  elif 'This is correct' in text:
    print("correct")
Run Code Online (Sandbox Code Playgroud)

这将适用于正确之前的任何字母组合...例如fkrjCorrect,4123Correct和lolcorrect将在if语句中返回true.当我希望它回归真实时,如果它完全匹配"这是正确的"

Bir*_*rei 14

您可以使用正则表达式的单词边界.例:

import re

s = '98787This is correct'
for words in ['This is correct', 'This', 'is', 'correct']:
    if re.search(r'\b' + words + r'\b', s):
        print('{0} found'.format(words))
Run Code Online (Sandbox Code Playgroud)

产量:

is found
correct found
Run Code Online (Sandbox Code Playgroud)

编辑:要完全匹配,请将\b断言替换为^$将限制匹配到行的开头和结尾.


Ter*_*ryA 13

使用比较运算符==而不是in:

if text == 'This is correct':
    print("Correct")
Run Code Online (Sandbox Code Playgroud)

这将检查整个字符串是否正好'This is correct'.如果不是,那就是False

  • 这是不正确的,因为我需要它来检查一个句子...而不只是一个字符串...所以该句子可能是“这是美好的一天,这是正确的!” (4认同)
  • @user2750103 尝试`import re; 如果 re.search('\bThis is correct\b') 不是 None: print('correct')` (2认同)

Sim*_*lan 7

我怀疑您正在寻找该startswith()功能。这检查字符串中的字符是否与另一个字符串的开头匹配

"abcde".startswith("abc") -> true

"abcde".startswith("bcd") -> false
Run Code Online (Sandbox Code Playgroud)

还有一个endswith()功能,用于在另一端检查。


sha*_*hmo 5

实际上,您应该寻找被单词边界包围的“这是正确的”字符串。

所以

import re

if re.search(r'\bThis is correct\b', text):
    print('correct')
Run Code Online (Sandbox Code Playgroud)

应该为你工作。