Testing if string contains a substring

Roy Smith roy at panix.com
Wed Apr 23 16:58:07 CEST 2003


Frantisek Fuka  <fuka at fuxoft.cz> wrote:
>I want a simple test to see if str contains any occurences of substr. I 
>am currently using this:
>
>import string
>if string.find(str,substr) + 1:
>     ...do something...
>
>But it somehow looks "ugly" to me. Is there more "standard" way to test 
>this?

My first comment would be that adding 1 to the result of string.find
is quite ugly.  The code is much more readable if you simply test for
equality to -1.

Next, the string module is rather out-dated.  It's nicer to use the
new (in 2.0, I think) string methods.  So you end up with:

if str.find (substr) == -1:
   do something

which I think is pretty clean.





More information about the Python-list mailing list