Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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:
like image 817
Parseltongue Avatar asked Jul 01 '11 01:07

Parseltongue


People also ask

How do you check if multiple values are in a string?

Use the any() function to check if multiple strings exist in another string, e.g. if any(substring in my_str for substring in list_of_strings): . The any() function will return True if at least one of the multiple strings exists in the string.

How do I check if a string contains in Python?

Python uses many methods to check a string containing a substring like, find(), index(), count(), etc. The most efficient and fast method is by using an “in” operator which is used as a comparison operator.

How do you check if a string contains two strings in Python?

You can use any : a_string = "A string is more than its parts!" matches = ["more", "wholesome", "milk"] if any(x in a_string for x in matches): Similarly to check if all the strings from the list are found, use all instead of any . any() takes an iterable.

How do you check if a string does not contain a character in Python?

Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .


2 Answers

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.

like image 113
li.davidm Avatar answered Oct 05 '22 23:10

li.davidm


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')
like image 38
jcomeau_ictx Avatar answered Oct 06 '22 00:10

jcomeau_ictx