首页 > Python > 我在 Python 中的堆栈溢出问题

我在 Python 中的堆栈溢出问题

上一篇 下一篇

网友问题:

我在 Python 中的 or 方法。string.containsstring.indexof

我想做:

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

———————————–

网友回答:

如果只是一个子字符串搜索,您可以使用 .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

—————————————-

网友回答:

使用运算符:in

if "blah" not in somestring: 
    continue

———————————————

网友回答:

Python 有字符串包含子字符串的方法吗?

99% 的用例将使用关键字 来覆盖,该关键字返回或 :inTrueFalse

'substring' in any_string

对于获取索引的用例,请使用(失败时返回 -1,并具有可选的位置参数):str.find

start = 0
stop = len(any_string)
any_string.find('substring', start, stop)

或(喜欢但在失败时引发 ValueError):str.indexfind

start = 100 
end = 1000
any_string.index('substring', start, end)

解释

使用比较运算符,因为in

  1. 该语言打算使用它,并且
  2. 其他Python程序员会希望你使用它。
>>> 'foo' in '**foo**'
True

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

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

这在语义上与 相同,但它更具可读性,并且在语言中明确提供,作为可读性的改进。not 'foo' in '**foo**'

避免使用__contains__

“包含”方法实现 的行为。这个例子,in

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

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

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

但不要。以下划线开头的方法在语义上被视为非公共方法。使用它的唯一原因是在实现或扩展 and 功能时(例如,如果子类化):innot instr

class NoisyString(str):
    def __contains__(self, other):
        print(f'testing if "{other}" in "{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

不要使用 和 测试“包含”findindex

不要使用以下字符串方法来测试“包含”:

>>> '**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

此外,这些不是 的直接替代品。您可能必须处理异常或情况,如果它们返回(因为它们在开头找到了子字符串),则布尔解释代替 .in-10FalseTrue

如果你真的是故意的,那就说出来。not any_string.startswith(substring)

性能比较

我们可以比较实现同一目标的各种方法。

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'))),
}

And now we see that using is much faster than the others.
Less time to do an equivalent operation is better:
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}

How can be faster than if uses ?in__contains__in__contains__

This is a fine follow-on question.

Let’s disassemble functions with the methods of interest:

>>> from dis import dis
>>> dis(lambda: 'a' in 'b')
  1           0 LOAD_CONST               1 ('a')
              2 LOAD_CONST               2 ('b')
              4 COMPARE_OP               6 (in)
              6 RETURN_VALUE
>>> dis(lambda: 'b'.__contains__('a'))
  1           0 LOAD_CONST               1 ('b')
              2 LOAD_METHOD              0 (__contains__)
              4 LOAD_CONST               2 ('a')
              6 CALL_METHOD              1
              8 RETURN_VALUE

因此,我们看到必须单独查找该方法,然后从Python虚拟机调用 – 这应该足以解释差异。.__contains__

模板简介:该模板名称为【我在 Python 中的堆栈溢出问题】,大小是暂无信息,文档格式为.html,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。

相关搜索
  • 下载密码 lanrenmb
  • 下载次数 177次
  • 使用软件 Sublime/Dreamweaver/HBuilder
  • 文件格式 html
  • 文件大小 暂无信息
  • 上传时间 02-07
  • 作者 网友投稿
  • 肖像权 人物画像及字体仅供参考
栏目分类 更多 >
热门推荐 更多 >
自适应 微信图片 单页式简历模板 微信文章 微信素材 微信公众平台 企业网站 html5 响应式 微信模板
您可能会喜欢的其他模板