Strings 15-112 Fundamentals of Programming 9/30/2013

advertisement
9/30/2013
Strings
Strings are immutable
15-112 Fundamentals of
Programming
September 26th , 2013
String Functions
s.count(sub) – Count the number of
occurrences of sub in s
name = “Daun Chuung"
print name.count(“u")
print name.count(“uu")
 Once created, a string itself cannot be
changed
 You can assign a different string to an existing
variables
name = “Daun Chung"
name.lower()
print name
name = name.lower()
print name
String Functions
s.find(sub) Find the first index of sub in s,
or -1 if not found
name = “Yasser El-Sayed"
print name.find(“El")
print name.find(“ “)
print name.find(“Yasser")
print name.find(“yasser")
1
9/30/2013
String Functions
s.index(sub) – find the first index of sub in
s or error if not found
name = “Yasser El-Sayed"
print name.find(“El")
print name.find(“ “)
print name.find(“Yasser")
print name.find(“yasser")
String Functions
s.split() – Returns a list of words in s
name = “Muhammad Ali Najeeb Qazi"
eachName = name.split()
print eachName
OUTPUT  [‘Muhammad', ‘Ali', ‘Najeeb‘, ‘Qazi’]
String Functions
s.rfind(sub) – Find the last index of sub in
s or -1 if not found
s.rindex(sub) – Find the last index of sub
in s or Error if not found
String Functions
s.join(lst) – Join the list of words into a
single string using s as separator
a = ["Harry", "Potter","and","the","goblet","of","fire"]
t=""
print t.join(a)  Harry Potter and the goblet of fire
t = “..”
print t.join(a) 
Harry..Potter..and..the..goblet..of..fire
2
9/30/2013
What is HTML?
Hyper Text Markup Language
<HTML>
<TITLE> Hello World </TITLE>
<H1> Welcome to My Webpage </H1>
How does the www work?
You enter a URL in the address bar of
your web browser
The web browser fetches the index.html
file from that location
Index.html file has HTML code that is
displayed by the web browser
<img src="melatest.jpg“>
</HTML>
Reading webpages
We can read web pages using Python
We use the library called urllib
Open a url by using urlopen
p = urllib.urlopen("http://www.cnn.com")
line = p.readline()
while line:
print line
line = p.readline()
Let’s Try this
Read UPC barcode from user and display the
item using http://www.upcdatabase.com
import urllib
upc = raw_input("Enter UPC> ")
p = urllib.urlopen("http://www.upcdatabase.com/item/"+upc)
line = p.readline()
while line:
if "Description" in line:
line = line.replace("Description","")
line = line.replace("<td>","")
line = line.replace("</td>","")
line = line.replace("<tr>","")
line = line.replace("</tr>","")
print line
line = p.readline()
3
Download