What statemen should i use for this kind of task:
I need finde if string variable a
is in string variable b
.
What should I use?
What statemen should i use for this kind of task:
I need finde if string variable a
is in string variable b
.
What should I use?
if a in b:
# ...found it, do stuff...
or
if b.find(a) != -1:
# ...found it, do stuff...
The former is probably more pythonic, but the latter lets you catch issues sooner if a or b are not the types you were expecting, since if a
or b
aren't strings, the latter will always fail non-silently, whereas the former can misbehave silently in some cases (for instance, 'foo' in ['foobar']
or even 'foo' in [1,2,3]
).
How about
if a in b:
print "a is in b"
If you also want to ignore capitals:
if a.lower() in b.lower():
print "a is in b"
Strings are treated like lists of characters in Python. Therefore, the following will work whether a is a character and b is a string or if a is an element type and b is a list:
if a in b:
#foo
else:
#bar
(Internally, Python handles strings and lists differently, but you can treat them as the same thing in many operations, like list comprehensions).
>>> a = '1324'
>>> b = '58132458495'
>>> if a in b:
print(True)
>>> True