Unit-3 - text and file processing
Unit-3 - text and file processing
67
Strings
string: A sequence of text characters in a program.
Strings start and end with quotation mark " or apostrophe ' characters.
Examples:
"hello"
"This is a string"
"This, too, is a string. It can be very long!"
A string may not span across multiple lines or contain a " character.
"This is not
a legal String."
"This is not a "legal" String either."
68
Indexes
Characters in a string are numbered with indexes starting at 0:
Example:
name = "P. Diddy"
index 0 1 2 3 4 5 6 7
character P . D i d d y
Example:
print name, "starts with", name[0]
Output:
P. Diddy starts with P
69
String properties
len(string) - number of characters in a string
(including spaces)
str.lower(string) - lowercase version of a string
str.upper(string) - uppercase version of a string
Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print big_name, "has", length, "characters"
Output:
MARTIN DOUGLAS STEPP has 20 characters
70
raw_input
raw_input : Reads a string of text from user input.
Example:
name = raw_input("Howdy, pardner. What's yer name? ")
print name, "... what a silly name!"
Output:
Howdy, pardner. What's yer name? Paris Hilton
Paris Hilton ... what a silly name!
71
Text processing
text processing: Examining, editing, formatting text.
often uses loops that examine the characters of a string one by one
72
Strings and numbers
ord(text) - converts a string into a number.
Example: ord("a") is 97, ord("b") is 98, ...
73
File processing
Many programs handle data, which often comes from files.
Example:
file_text = open("bankaccount.txt").read()
74
Line-by-line processing
Reading a file line-by-line:
for line in open("filename").readlines():
statements
Example:
count = 0
for line in open("bankaccount.txt").readlines():
count = count + 1
print "The file contains", count, "lines."
75