**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:
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.
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.
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.
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 .
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With