sep 16
Questions?
#aside for davey:
numbers = [11 12, 13]
letters = ['h', 'i']
double = map(lambda x: 2*x, numbers) # gives [22, 24, 26]
concat = reduce(lambda x,y: x+y, ['h', 'e', 'l', 'l', 'o']) # gives "hi"
# but last is better as
''.join(letters)
Documentation links on resources page :
Finish chap 4:
1. bunch of string operations; see pg 48 of Zelle.
import string
text = "This is some text."
text_list = list(text) # ['T', 'h', ...]
back_to_text = string.join(text_list, '')
hello_there = "hello" + " " + "there"
number = ascii('h')
letter = chr(number)
2. Making the output look nice: text formatting : %i, %f, %d, %s within format strings, using "%" operator on strings.
print "Compare %f and %0.20f \n" % (3.14, 3.14)
3. Files
I file is essentially a list of lines. Once you've "opened" one, you can read from it and/or print to it.
inputfile = open("filename_here", "r") # 'r' for 'read' access', i.e. input, 'w' for 'write access', i.e. output
# Input: use one of these three :
whole_file = inputfile.read()
next_line = inputfile.readline()
array_of_lines = inputfile.readlines()
outputfile = open("other_filename_here", "w')
outputfile.write("this will be the first line in that file. \n")
4. ascii : numeric values for 1 byte characters;
- wikipedia: ascii
- printable are 32 (space) through 176 (~).
- In python: ord(char) converts a character (e.g. 'a') to its ascii number (e.g. 97).
- To do the opposite, chr(97) gives 'a'
Putting all this together you get a very typical program :
- open a file
- read stuff in (typically text or numbers)
- do something to it (put it into a secret code, for example)
- write it back out
Example: do file conversion rot13 in class
- see wikipedia:rot13
- Ask for input file name
- create file with same name, but 'rot13_' on front.
- Read input to a string.
- In a loop, convert (and store) the thing to its rot13 version
- Output new string to new file
Here's what we created in class :
# rot13.py
# Example of rot13 text transform
# Jim M , Sep 16 2010 (in class)
#
import string
def main():
# 1. Get the text to be transformed.
text = raw_input("What is the (lowercase) word? ")
# 2. Convert the text to rot13.
rot13_text = ""
for char in text:
number = ord(char) - ord('a')
# print " debug: number = ", number
rot13_number = (number + 13) % 26
# print " debug: rot13_number + ", rot13_number
new_char = chr(rot13_number + ord('a'))
# print " debug: new_char = '%s' " % new_char
rot13_text = rot13_text + new_char
# 3. Output the text.
print "rot13='%s'" % rot13_text
main()