7

**Note- I will not just be testing at the end of a string-- need to locate particular substrings anywhere in the string

What is the fastest way to check to make sure a string does not contain multiple values. My current method is inefficient and unpythonic:

if string.find('png') ==-1 and sring.find('jpg') ==-1 and string.find('gif') == -1 and string.find('YouTube') == -1:
Parseltongue
  • 11,157
  • 30
  • 95
  • 160
  • 1
    possible duplicate of [Check if multiple strings exist in another string](http://stackoverflow.com/questions/3389574/check-if-multiple-strings-exist-in-another-string) – Piotr Dobrogost Sep 28 '12 at 18:55

3 Answers3

16

Try:

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

which is basically the same as your code, but more elegantly written.

li.davidm
  • 11,736
  • 4
  • 29
  • 31
8

if you're testing just the end of the string, remember that str.endswith can accept a tuple.

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

otherwise:

>>> import re
>>> re.compile('jpg|png|gif').search('testpng.txt')
<_sre.SRE_Match object at 0xb74a46e8>
>>> re.compile('jpg|png|gif').search('testpg.txt')
jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107
-4

You could also do something like this if the values to test for didn't need to be managed by a tuple/list.

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

EDIT I see the error of my ways now, it only checks the first.

>>> ('bees' or 'png' or 'jpg' or 'foo') in 'testpng.txt'
False
Philip Southam
  • 15,843
  • 6
  • 28
  • 20
  • That doesn't work - the `'jpg' or 'png' or...` evaluates to `True`, which is then negated - you are testing for the presence of `False` in the string. – li.davidm Jul 01 '11 at 01:54
  • That *still* won't work: the `or` also converts the strings into booleans; you are now simply testing for `True` in the string. – li.davidm Jul 01 '11 at 02:21