Python:在字符串中找到精确的短语

时间:2018-05-08 12:09:00

标签: python regex string

我对字符串操作不是很熟悉,我试图找到一种方法来确定,如果给出一个文本字符串和一个短语,该短语是否会按照给定的顺序出现在字符串中。

例:
string='This question will probably be down voted because I am not able to post a minimal, complete, and verifiable example.'

phrase='I will not be down voted.'

由于phrase string中的if 'seek' in 'those who seek shall find': print('Success!') 出现的顺序不同,因此不匹配。我知道有可能找到一个单词是否是字符串的一部分,例如:

{{1}}

但如何检查整个短语是否以原始顺序出现在字符串中?

3 个答案:

答案 0 :(得分:3)

如果我做得对,你可以像在一个给定的字符串中找到一个单词那样做:

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

如果我对你所要求的内容有误,请纠正我。

答案 1 :(得分:1)

不确定我是否理解您的问题,但有人评论说,您可以使用关键字in来测试字符串中的特定词组:

'my specific phrase' in 'my string with my specific phrase'将返回True

但是'my specific phrase' in 'my string specific phrase'会返回False,因为即使单词存在,它们的顺序也不一样。

答案 2 :(得分:1)

我能想到三种方式:

  1. 在opetor中:

    字符串中的

    阶段

  2. 2.使用string.find(substring) - 如果相位不在字符串中,则返回None。

    1. 使用re.search - re是python中的包
    2. re.search(pattern,string)

相关问题