tags:

views:

207

answers:

3

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

I want to do:

if not somestring.contains("blah"):
   continue
+4  A: 

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."

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.

eldarerathis
+1 for highlighting the gotchas involved in substring searches. the obvious solution is `if ' is ' in s:` which will return `False` as is (probably) expected.
aaronasterling
+13  A: 

You can use the in operator:

if not "blah" in somestring: continue
Michael Mrozek
This doesn't seem to work in Python 3.1 -- is there another way?
Casey
@Casey It works in 3.1; what error are you getting?
Michael Mrozek
@Casey, what are you saying? It works just fine in 3.1, like in 2.any. Comments are really unsuitable for posting any substantial amount of code, so I recommend you ask another question with a clear, simple, short, complete example of what you think "doesn't seem to work in Python 3.1", and I predict you'll be set right extremely fast about what is really the problem w/your code;-).
Alex Martelli
@Casey, Michael, Alex, It doesn't work in Python3.1 if you are mixing `byte` and `str` types. Perhaps that is the problem
gnibbler
In my case this didn't work because I was searching a string for newline characters. Turns out that in 3.1 you must use the code -- if r"\n" in somestring -- I didn't post a new question because I wasn't if what I was experiencing was exclusive to Python 3.1 (At the time I hadn't installed 2.7 yet)
Casey
@Casey If "\n" in "foo\nbar" works fine for me in 3.1, but I guess as long as you fixed your problem it doesn't matter
Michael Mrozek
+5  A: 

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.

Alex Martelli