O'Reilly logo

A Concise Introduction to Programming in Python by Mark J. Johnson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 16

String Methods

Files are not limited to those on your hard drive. The following program retrieves a web page from the Internet, and then uses Python’s string methods to display specific information from it.

Listing 16.1: GCS Menu

 1 # menu.py
 2
 3 import urllib.request
 4
 5 URL = "http://www.central.edu/go/gcsmenu"
 6
 7 def getpage(url):
 8 with urllib.request.urlopen(url) as f:
 9  return str(f.read())
10
11 def gettag(page, tag, start=0):
12 opentag = "<" + tag + ">"
13 closetag = "</" + tag + ">"
14 i = page.find(opentag, start)
15 if i == −1:
16  return None, i
17 j = page.find(closetag, i)
18 return page[i + len(opentag):j], j
19
20 def process(page):
21 heading, i = gettag(page, "h2")
22 result = "\n" + heading.center(60) + ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required