I'm looking for a string.contains
or string.indexof
method in Python.
I want to do:
if not somestring.contains("blah"): continue
You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
Python string __contains__() is an instance method and returns boolean value True or False depending on whether the string object contains the specified string object or not. Note that the Python string contains() method is case sensitive.
You can use the in
operator:
if "blah" not in somestring: continue
If it's just a substring search you can use string.find("substring")
.
You do have to be a little careful with find
, index
, and in
though, as they are substring searches. In other words, this:
s = "This be a string" if s.find("is") == -1: print("No 'is' here!") else: print("Found 'is' in the string.")
It would print Found 'is' in the string.
Similarly, if "is" in s:
would evaluate to True
. This may or may not be what you want.
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