I find myself repeatedly writing the same chunk of code:
def stringInList(str, list):
retVal = False
for item in list:
if str in item:
retVal = True
return retVal
Is there any way I can write this function quicker/with less code? I usually use this in an if statement, like this:
if stringInList(str, list):
print 'string was found!'
The easiest way to check if a Python string contains a substring is to use the in operator. The in operator is used to check data structures for membership in Python. It returns a Boolean (either True or False ).
Yes, use any()
:
if any(s in item for item in L):
print 'string was found!'
As the docs mention, this is pretty much equivalent to your function, but any()
can take generator expressions instead of just a string and a list, and any()
short-circuits. Once s in item
is True, the function breaks (you can simply do this with your function if you just change retVal = True
to return True
. Remember that functions break when it returns a value).
You should avoid naming strings str
and lists list
. That will override the built-in types.
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