Asked : Nov 17
Viewed : 23 times
I'm looking for a string.contains
or string.indexof
method in Python.
I want to do:
if not somestring.contains("blah"):
continue
Nov 17
You can use the in
operator:
if "blah" not in somestring:
continue
answered Jan 25
if needle in haystack:
is the normal use, as @Michael says -- it relies on the in
operator, more readable and faster than a method call.
If you truly need a method instead of an operator (e.g. to do some weird key=
for a very peculiar sort...?), that would be 'haystack'.__contains__
. But since your example is for use in an if
, I guess you don't really mean what you say;-). It's not good form (nor readable, nor efficient) to use special methods directly -- they're meant to be used, instead, through the operators and builtins that delegate to them.
answered Jan 25
You can use y.count()
.
It will return the integer value of the number of times a sub string appears in a string.
For example:
string.count("bah") >> 0
string.count("Hello") >> 1
answered Jan 25
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
). To check if a string contains a substring in Python using the in
operator, we simply invoke it on the superstring:
fullstring = "StackAbuse"
substring = "tack"
if substring in fullstring:
print("Found!")
else:
print("Not found!")
answered Jan 25