Skip to content Skip to sidebar Skip to footer

Check To Ensure A String Does Not Contain Multiple Values

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

Solution 1:

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.


Solution 2:

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

Solution 3:

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

Post a Comment for "Check To Ensure A String Does Not Contain Multiple Values"