Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have a string 'contains' substring method?

I'm looking for a string.contains or string.indexof method in Python.

I want to do:

if not somestring.contains("blah"):    continue 
like image 475
Blankman Avatar asked Aug 09 '10 02:08

Blankman


People also ask

Does string contain substring?

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.

Does Python have a Contains method?

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.


2 Answers

You can use the in operator:

if "blah" not in somestring:      continue 
like image 141
Michael Mrozek Avatar answered Oct 05 '22 14:10

Michael Mrozek


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.

like image 22
eldarerathis Avatar answered Oct 05 '22 16:10

eldarerathis