[Tutor] Finding text in a long string
Magnus Lyckå
magnus@thinkware.se
Tue Jun 17 07:20:04 2003
At 22:51 2003-06-16 -0400, Timothy M. Brauch wrote:
>I tried some things like:
>
>data = urllib.urlopen(ADDRESS).read()
>if "image1.gif" in data:
> print "Success"
>else: print "Failure
This is somewhat easier than some other replies might suggest.
First of all, if you upgrade to the Python 2.3 beta, the code
above will work. Normally, the in-operator checks whether the
first operand is equal to any element in the sequence that is
given as right operand (and a string is a sequence of one
character strings), but for strings on both sides, this is
being changed in Python 2.3 to do a substring search.
For now, the simplest way is to use the .find method. It returns
the location where the searched substring begins, and -1 if it's
not found at all. In other words:
subString = "image2.gif"
if data.find(subString) != -1:
print "Found", subString
else:
print "Didn't find", subString
--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The Agile Programming Language