[Tutor] Finding text in a long string

David Broadwell dbroadwell@mindspring.com
Tue Jun 17 01:45:03 2003


> I'm sure that there are better ways of doing what you want than what I am
> recommending, but here goes anyway:
>
> 1. Use the startswith() method for strings. Unfortunately this means you
> have to test this at every position in the string.
> for i in range(len(data)):
>          if data[i:].startswith("image1.gif"):
>              print "Success"
I had considered mentioning seeking '.' and using a offset to match
'image1.gif' but decided against. I'm rather green ... you stated a
similar idea far better than I.

> 2. Same approach but reduce the work required by checking first if the
> first letter matches:
> for i in range(len(data)):
>          if data[i]=='i' and data[i:].startswith("image1.gif"):
>              print "Success"
Nice pattern ...
I'll have to do more testing on the;
if <cond1> and <cond2>: pass

which if i am correct equates to;
if <cond1>:
    if <cond2>:
        pass

Given that it may not always evaluate <cond2>, is that always correct?

> 3. As David Broadwell suggested, you can divide data further. Since
> "image1.gif" will always be part of a URL, it will always have '/' before
> it. You can therefore split data using '/'
>
> newdata = data.split('/')
> for phrase in newdata:
>          if phrase.startswith("image1.gif"):
>              print "Success"
>
This is what i LOVE about python, it can be read.

--

David Broadwell