检查字符串是否不包含多个值
**注意 - 我不仅仅是在检查字符串的末尾,我需要在字符串的任何位置找到特定的子字符串。
有没有什么快速的方法可以检查一个字符串中是否不包含多个特定的值?我现在的方法效率低下,而且不太符合Python的风格:
if string.find('png') ==-1 and sring.find('jpg') ==-1 and string.find('gif') == -1 and string.find('YouTube') == -1:
3 个回答
-4
如果你要测试的值不需要用元组或列表来管理,你也可以这样做。
>>> ('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
16
试试这个:
if not any(extension in string for extension in ('jpg', 'png', 'gif')):
这个代码基本上和你的代码是一样的,但写得更简洁优雅。
8
如果你只是想检查字符串的结尾,记得 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')