Page 93 -
P. 93
finding the deal
You needed to update your price-grabbing program so that it extracts the four-character
substring that follows the occurence of the “>$” characters.
Hints: Don’t forget that the find() method finds the starting position of a substring. Once
you’ve found “>$”, use Python’s addition operator to calculate where in the string you want to
extract the substring. The addition operator is the “+” symbol.
import urllib.request
This code
hasn’t
changed. page = urllib.request.urlopen(“http://www.beans-r-us.biz/prices.html")
text = page.read().decode(“utf8")
Search for the index location
of the “>$" combination. where = text.find(‘>$')
This is the addition operator.
start_of_price = where + 2
The start of the actual price
is another 2 index positions end_of_price = start_of_price + 4
along the string, while the end
of the price is another 4.
price = text[start_of_price:end_of_price]
print(price)
With the start and end index
Did you remember to locations known, it’s easy to
print out the price specify the substring required.
once you’d found it?
58 Chapter 2