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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18632491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:16:55  来源:igfitidea点击:

How do I check for an EXACT word in a string in python

pythonstring

提问by user2750103

Basically I need to find a way to figure out a way to find the EXACT word in a string. All the information i have read online has only given me how to search for letters in a string so

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

98787This is correct

98787这是正确的

will still come back as true in an if statement.

仍然会在 if 语句中返回为真。

This is what I have so far.

这是我到目前为止。

  elif 'This is correct' in text:
    print("correct")

This will work with any combination of letters before the Correct... For example fkrjCorrect, 4123Correct and lolcorrect will all come back as true in the if statement. When I want it to come back as true only IF it exactly matches "This is correct"

这将适用于正确之前的任何字母组合...例如,fkrjCorrect、4123Correct 和 lolcorrect 在 if 语句中都将返回为真。当我希望它仅在它与“这是正确的”完全匹配时才返回真实

回答by TerryA

Use the comparison operator ==instead of inthen:

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

if text == 'This is correct':
    print("Correct")

This will check to see if the whole string is just 'This is correct'. If it isn't, it will be False

这将检查整个字符串是否只是'This is correct'. 如果不是,它将是False

回答by Birei

You can use the word-boundaries of regular expressions. Example:

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

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))

That yields:

这产生:

is found
correct found


EDIT: For an exact match, replace \bassertions with ^and $to restrict the match to the begin and end of line.

EDIT:对于完全匹配,替换\b使用断言^$所述开始和线路的端部以限制匹配。

回答by Bor

You can make a few changes.

您可以进行一些更改。

elif 'This is correct' in text[:len('This is correct')]:

or

或者

elif ' This is correct ' in ' '+text+' ':

Both work. The latter is more flexible.

两者都有效。后者更灵活。

回答by Simon Callan

I suspect that you are looking for the startswith()function. This checks to see if the characters in a string match at the start of another string

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

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

"abcde".startswith("bcd") -> false

There is also the endswith()function, for checking at the other end.

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

回答by sharcashmo

Actually, you should look for 'This is correct' string surrounded by word boundaries.

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

So

所以

import re

if re.search(r'\bThis is correct\b', text):
    print('correct')

should work for you.

应该为你工作。

回答by Toshiro

Break up the string into a list of strings with .split() then use the in operator.

使用 .split() 将字符串分解为字符串列表,然后使用 in 运算符。

This is much simpler than using regular expressions.

这比使用正则表达式简单得多。

回答by Jash Enakulapati

Below is a solution without using regular expressions. The program searches for exact word in this case 'CASINO' and prints the sentence.

以下是不使用正则表达式的解决方案。程序在本例中搜索确切的单词“CASINO”并打印句子。

    words_list = [ "The Learn Python Challenge Casino.", "They bought a car while at 
    the casino", "Casinoville" ]
    search_string = 'CASINO'
    def text_manipulation(words_list, search_string):
        search_result = []
        for sentence in words_list:
            words = sentence.replace('.', '').replace(',', '').split(' ')
            [search_result.append(sentence) for w in words if w.upper() == 
              search_string]
        print(search_result)

    text_manipulation(words_list, search_string)

This will print the results - ['The Learn Python Challenge Casino.', 'They bought a car while at the casino']

这将打印结果 - ['The Learn Python Challenge Casino.', '他们在赌场买了一辆车']