Testing if string contains a substring

Henrik Härkönen" <radix at kortis.to> Henrik Härkönen" <radix at kortis.to>
Wed Apr 23 10:28:04 EDT 2003


On Wed, 23 Apr 2003 15:44:57 +0200, Frantisek Fuka 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?

Well, there are number of ways I guess, but after cleaning up a bit it 
could look like this:

if str.count(substr) > 0:
    do_stuff()

and where the 'str' is the string variable wanted to be checked of
occurances of 'substr', using string-methods. So you don't have to
import string module, but of course, if using old interpreter, you must do
it the old way.


Henrik




More information about the Python-list mailing list