首页 文章

Python有一个字符串'contains' substring方法吗?

提问于
浏览
3220

我正在寻找Python中的 string.containsstring.indexof 方法 .

我想要做:

if not somestring.contains("blah"):
   continue

15 回答

  • 109

    使用布尔返回值(即 True 或`False)查找字符串是否包含少量字符的另一种方法:

    str1 = "This be a string"
    find_this = "tr"
    if find_this in str1:
        print find_this, " is been found in ", str1
    else:
        print find_this, " is not found in ", str1
    
  • 11

    如果你对 "blah" in somestring 感到满意,但希望它是一个函数调用,你可以这样做

    import operator
    
    if not operator.contains(somestring, "blah"):
        continue
    

    Python中的所有运算符都可以在operator module中找到或多或少,包括 in .

  • 140

    你可以使用in operator

    if "blah" not in somestring: 
        continue
    
  • 8

    我看到已有答案,但我想加上我的两分钱 .

    在Python中有一些函数可以做到这一点,但最简单(也是最受欢迎)的方法是使用关键字 in

    "test" in "testtext"
    True
    
    "abc" in "abcdefg"
    True
    
    "abc" in "Abc"
    False
    
    "ABC" in "abc"
    False
    
    "abc" in "def"
    False
    
    "abc" in ["abc", "def", "ghi"]
    True
    

    还有一些字符串方法:

    "xxabcxx".find("abc")
    2 # Returns the index of the first match
    
    "xxabcxx".find("cde")
    -1 # Returns -1 if the substring 
    # could not be found in the string
    
    # And:
    
    "xxabcxx".index("abc")
    2
    
    "xxabcxx".index("cde")
    ValueError: substring not found
    #raises ValueError...
    

    关于表现:

    通常 in 是查找子字符串的最快方法...

    find 略快于 index .

  • 4843

    Python有一个字符串包含substring方法吗?

    是的,但是Python有一个比较运算符,你应该使用它,因为语言意图使用它,而其他程序员会期望你使用它 . 该关键字是 in ,用作比较运算符:

    >>> 'foo' in '**foo**'
    True
    

    原始问题要求的相反(补语)是 not in

    >>> 'foo' not in '**foo**' # returns False
    False
    

    这在语义上与_75225相同,但它在语言中更具可读性和显式性,作为可读性改进 .

    避免使用__contains __,find和index

    正如所承诺的,这是 contains 方法:

    str.__contains__('**foo**', 'foo')
    

    返回 True . 您也可以从超级字符串的实例调用此函数:

    '**foo**'.__contains__('foo')
    

    但不要 . 以下划线开头的方法在语义上被认为是私有的 . 使用此功能的唯一原因是扩展 innot in 功能(例如,如果子类化 str ):

    class NoisyString(str):
        def __contains__(self, other):
            print('testing if "{0}" in "{1}"'.format(other, self))
            return super(NoisyString, self).__contains__(other)
    
    ns = NoisyString('a string with a substring inside')
    

    现在:

    >>> 'substring' in ns
    testing if "substring" in "a string with a substring inside"
    True
    

    另外,请避免使用以下字符串方法:

    >>> '**foo**'.index('foo')
    2
    >>> '**foo**'.find('foo')
    2
    
    >>> '**oo**'.find('foo')
    -1
    >>> '**oo**'.index('foo')
    
    Traceback (most recent call last):
      File "<pyshell#40>", line 1, in <module>
        '**oo**'.index('foo')
    ValueError: substring not found
    

    其他语言可能没有直接测试子字符串的方法,因此您必须使用这些类型的方法,但使用Python时,使用 in 比较运算符会更有效 .

    性能比较

    我们可以比较实现相同目标的各种方式 .

    import timeit
    
    def in_(s, other):
        return other in s
    
    def contains(s, other):
        return s.__contains__(other)
    
    def find(s, other):
        return s.find(other) != -1
    
    def index(s, other):
        try:
            s.index(other)
        except ValueError:
            return False
        else:
            return True
    
    
    
    perf_dict = {
    'in:True': min(timeit.repeat(lambda: in_('superstring', 'str'))),
    'in:False': min(timeit.repeat(lambda: in_('superstring', 'not'))),
    '__contains__:True': min(timeit.repeat(lambda: contains('superstring', 'str'))),
    '__contains__:False': min(timeit.repeat(lambda: contains('superstring', 'not'))),
    'find:True': min(timeit.repeat(lambda: find('superstring', 'str'))),
    'find:False': min(timeit.repeat(lambda: find('superstring', 'not'))),
    'index:True': min(timeit.repeat(lambda: index('superstring', 'str'))),
    'index:False': min(timeit.repeat(lambda: index('superstring', 'not'))),
    }
    

    现在我们看到使用 in 比其他人快得多 . 更少的时间进行等效操作更好:

    >>> perf_dict
    {'in:True': 0.16450627865128808,
     'in:False': 0.1609668098178645,
     '__contains__:True': 0.24355481654697542,
     '__contains__:False': 0.24382793854783813,
     'find:True': 0.3067379407923454,
     'find:False': 0.29860888058124146,
     'index:True': 0.29647137792585454,
     'index:False': 0.5502287584545229}
    
  • 24

    不,没有任何 string.contains(str) 方法,但有 in 运算符:

    if substring in someString:
        print "It's there!!!"
    

    这是一个更复杂的工作示例:

    # Print all files with dot in home directory
    import commands
    (st, output) = commands.getstatusoutput('ls -a ~')
    print [f for f in output.split('\n') if '.' in f ]
    
  • 10

    在Python字符串和列表中

    以下是一些有关 in 方法的有用示例:

    "foo" in "foobar"
    True
    
    "foo" in "Foobar"
    False
    
    "foo" in "Foobar".lower()
    True
    
    "foo".capitalize() in "Foobar"
    True
    
    "foo" in ["bar", "foo", "foobar"]
    True
    
    "foo" in ["fo", "o", "foobar"]
    False
    

    警告 . 列表是可迭代的, in 方法作用于迭代,而不仅仅是字符串 .

  • 508

    基本上,您希望在Python中的字符串中查找子字符串 . 有两种方法可以在Python中搜索字符串中的子字符串 .

    Method 1: in operator

    您可以使用Python的 in 运算符来检查子字符串 . 它非常简单直观 . 如果在字符串else False 中找到子字符串,它将返回 True .

    >>> "King" in "King's landing"
    True
    
    >>> "Jon Snow" in "King's landing"
    False
    

    Method 2: str.find() method

    第二种方法是使用 str.find() 方法 . 在这里,我们在要找到子字符串的字符串上调用 .find() 方法 . 我们将子字符串传递给find()方法并检查其返回值 . 如果其值不是-1,则在字符串中找到子字符串,否则不会 . 返回的值是找到子字符串的索引 .

    >>> some_string = "valar morghulis"
    
    >>> some_string.find("morghulis")
    6
    
    >>> some_string.find("dohaeris")
    -1
    

    我建议你使用第一种方法,因为它更Pythonic和直观 .

  • 119

    如果它只是一个子字符串搜索,您可以使用 string.find("substring") .

    你必须要小心 findindexin ,因为它们是子串搜索 . 换句话说,这个:

    s = "This be a string"
    if s.find("is") == -1:
        print "No 'is' here!"
    else:
        print "Found 'is' in the string."
    

    它将打印 Found 'is' in the string. 同样, if "is" in s: 将评估为 True . 这可能是也可能不是你想要的 .

  • 65

    显然,对于矢量方式的比较,没有类似的东西 . 一种明显的Python方法是:

    names = ['bob', 'john', 'mike']
    any(st in 'bob and john' for st in names) 
    >> True
    
    any(st in 'mary and jane' for st in names) 
    >> False
    
  • 34

    这是你的答案:

    if "insert_char_or_string_here" in "insert_string_to_search_here":
        #DOSTUFF
    

    检查是否为假:

    if not "insert_char_or_string_here" in "insert_string_to_search_here":
        #DOSTUFF
    

    要么:

    if "insert_char_or_string_here" not in "insert_string_to_search_here":
        #DOSTUFF
    
  • 18

    如前所述,您可以像这样使用 in 运算符:

    >>> to_search_in = "String to search in"
    >>> to_search = "search"
    >>> print(to_search in to_search_in)
    True
    >>> print(to_search_in.find(to_search))
    10
    

    您还可以使用正则表达式来获取事件:

    >>> import re
    >>> print(re.findall(r'( |t)', to_search_in)) # searches for t or space
    ['t', ' ', 't', ' ', ' ']
    
  • 7

    在Python中,有两种简单的方法可以实现这一点:

    The Pythonic way: Using Python's 'in' Keyword-

    in 需要两个"arguments",一个在左边(子串),一个在右边,如果左边的参数包含在右边的参数中,则返回 True ,如果不包含,则返回 False .

    example_string = "This is an example string"
    substring = "example"
    print(substring in example_string)
    

    输出:

    True
    

    The non-Pythonic way: Using Python's str.find:

    find 方法返回字符串中字符串的位置,如果未找到则返回-1 . 但只需检查位置是否不是-1 .

    if example_string.find(substring) != -1:
        print('Substring found!')
    else:
        print('Substring not found!')
    

    输出:

    Substring found!
    
  • 0

    如果您正在寻找对整个单词不区分大小写的搜索,而不是另一个单词中包含的子字符串:

    import string
    
    s = 'This is my text example'
    if 'is' not in (word.lower() 
        for split_char in string.punctuation + string.whitespace 
        for word in s.split(split_char)):
        # do something
    
  • 9

    if needle in haystack: 是正常使用,如@Michael说 - 它依赖于in运算符,比方法调用更具可读性和更快速度 .

    如果你真的需要一个方法而不是一个操作符(例如,做一些奇怪的 key= 非常奇怪的那种......?),那就是'haystack'.contains . 但是因为你的例子是在_75210中使用的,我想你不是直接使用特殊方法的好形式(也不是可读的,也不是高效的) - 它们的意思是通过运算符和内置函数来使用委托给他们 .

相关问题