【问题标题】:Python: sub string searchPython:子字符串搜索
【发布时间】:2011-11-30 01:39:38
【问题描述】:

我正在尝试在字符串中搜索整个单词,但不知道该怎么做。

str1 = 'this is'
str2 ='I think this isnt right'
str1 in str2

给我True,但我希望它返回False。我该怎么做呢?谢谢。

我尝试了str2.find(str1), re.search(str1,str2),,但我没有让他们不返回任何内容或返回 False。

请帮忙。谢谢。

【问题讨论】:

    标签: python string search


    【解决方案1】:

    在正则表达式中使用\b 实体来匹配单词边界。

    re.search(r'\bthis is\b', 'I think this isnt right')
    

    【讨论】:

    • 好的。谢谢。如何使用 word1 = 'this is' 和 line1 = 'I think this ist right' 来概括这一点?
    • 呃,就像你概括其他任何事情一样:使用变量。你有什么问题?
    • 我有 str1 = 'this is' 和 str2 = '我认为这不对'。我的语法不起作用。重新搜索(str1,str2)。它给出了对象的位置。我怎么做是什么都不退货?谢谢。
    • @Pradeep:注意\br'\bthis is\b' 的开头和结尾。这些是单词边界。
    • @StevenRumbalski,是的,我明白了。如何传递变量而不是“这是”?谢谢。
    【解决方案2】:

    不带正则表达式使用sets 的另一种方式:

    set(['this', 'is']).issubset(set('I think this isnt right'.split(' ')))
    

    如果字符串真的很长,或者您要继续评估单词是否在集合中,这可能会更有效。例如:

    >>> words = set('I think this isnt right'.split(' '))
    >>> words
    set(['I', 'this', 'isnt', 'right', 'think'])
    >>> 'this' in words
    True
    >>> 'is' in words
    False
    

    【讨论】:

    • 我相信 Pradeep 会希望它返回 false:set(['this', 'is']).issubset(set('I think this thing is wrong'.split(' ')))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    相关资源
    最近更新 更多