【问题标题】:Check to ensure a string does not contain multiple values检查以确保字符串不包含多个值
【发布时间】:2011-09-26 10:24:53
【问题描述】:

**注意——我不会只在字符串的末尾进行测试——需要在字符串中的任何位置定位特定的子字符串

检查以确保字符串不包含多个值的最快方法是什么。我目前的方法效率低下且不合 Python:

if string.find('png') ==-1 and sring.find('jpg') ==-1 and string.find('gif') == -1 and string.find('YouTube') == -1:

【问题讨论】:

标签: python algorithm string


【解决方案1】:

如果要测试的值不需要由元组/列表管理,您也可以这样做。

>>> ('png' or 'jpg' or 'foo') in 'testpng.txt'
True
>>> ('png' or 'jpg' or 'foo') in 'testpg.txt'
False

编辑 我现在看到了我的方式的错误,它只检查第一个。

>>> ('bees' or 'png' or 'jpg' or 'foo') in 'testpng.txt'
False

【讨论】:

  • 这不起作用 - 'jpg' or 'png' or... 的计算结果为 True,然后被否定 - 您正在测试字符串中是否存在 False
  • still 不起作用:or 还将字符串转换为布尔值;您现在只是在字符串中测试True
【解决方案2】:

试试:

if not any(extension in string for extension in ('jpg', 'png', 'gif')):

这与您的代码基本相同,但写得更优雅。

【讨论】:

    【解决方案3】:

    如果您只测试字符串的结尾,请记住 str.endswith 可以接受元组。

    >>> "test.png".endswith(('jpg', 'png', 'gif'))
    True
    

    否则:

    >>> import re
    >>> re.compile('jpg|png|gif').search('testpng.txt')
    <_sre.SRE_Match object at 0xb74a46e8>
    >>> re.compile('jpg|png|gif').search('testpg.txt')
    

    【讨论】:

    • 不只是测试字符串的结尾 :-( 需要检测这些子字符串是否出现在任何地方。
    • 好的,那么正则表达式可能会更好;将修改答案
    猜你喜欢
    • 2021-11-07
    • 2014-12-27
    • 1970-01-01
    • 2012-05-12
    • 2014-06-25
    • 1970-01-01
    • 2013-10-26
    • 2013-02-05
    • 2012-05-06
    相关资源
    最近更新 更多