Thu Sep 17
next week
About the homework - some are tricky.
See what you can do.
The point isn't to get everything perfectly correct -
instead it's to explore these ideas, practice
manipulating the data, and dig in to the documentation.
Being stuck and/or confused is OK. Pay careful attention
to what the blockage is, and see if there's a away around
it - that's what you're really trying to learn.
Techniques to try :
- print everything you can think of, everywhere, to ensure it is all doing what you expect.
- slowly add tiny bits of code, seeing the program run differently each time
- google keywords or questions
- is there another thing you can do that's similar to this?
- ask a classmate, or Sam, or Jim
And I've given an example of something close to one of the homework
problems at the end of these notes.
back to strings
(Here we'll pick up from where we were
last time ... getting back to the cipher
stuff as time allows.)
Any questions from the reading or from
the ideas from Tues time?
string operations summary
There are many ways to manipulate strings in python.
'this ' + 'that' # concatenate
'x' * 10 # replicate
'This is a string'[0:3] # substrings; 'Thi'
len('string') # how many characters?
for char in the_string: # loop over characters
print char, ' is ', ord(char) # ... and do something with each
# lots more
import string # grab a bunch of 'em
dir(string) # list all the string.yyy() functions
dir("xxx") # what the the "xxx".method() things?
# conversions
x = float("32.3") # convert string to float
y = int("101") # convert string to int
z = str(anything) # convert anything to a string
eval("1+2") # evaluate string as python expression; return result
Discuss the name.method(arg1, arg2) convention we just started seeing.
We'll be getting lots more of that.
And remember the dir() trick to see what
.method() things there are for different things in the language.
More practice with string manipulations.
import string
text = "This is some text."
text_list = list(text) # ['T', 'h', ...]
test_list2 = string.split(text, '') # same thing
back_to_text = string.join(text_list, '')
hello_there = "hello" + " " + "there"
number = ord('h')
letter = chr(number)
word_dashes = 'one-two-three'
word_list = string.split(word_dashes, '-') # ['one', 'two', 'three']
word_commas = string.join(word_list, ',') # 'one,two,three'
Aside :
There are actually three 'places' that the string functions live, which can be confusing :
>>> number = ord('h') # built-in function
>>> import string
>>> string.upper('hello') # within the string module
Or just this :
>>> 'hello'.upper() # (!)
The last form we haven't talked about yet, but will do lots more with later.
(This is actually "object-oriented" programming, in which we think
of the string 'hello' as an "object" and upper as one of its "methods".)
Many of the string manipulations are available in both the string module
and as methods of strings. To see the difference
>>> import string # load the string module
>>> dir(string) # functions and variables in the string module
>>> dir('hello') # names that can be used as 'hello'.name
converting between lists and strings
Some operations are easier when working with a list
than a string. Python does allow you to convert between them.
>>> abc_string = 'abc'
>>> abc_list = list(abc_string) # ['a', 'b', 'c']
Going the other way isn't quite as easy.
>>> str(abc_list) # what do you think this is?
The python function is "join". Unfortunately,
it lives several places ... and has several calling conventions.
Here's the one I recommend.
>>> import string
>>> string.join(abc_list, "") # the 2nd arg is what to join with
a few class exercises
1. Can you change the characters in a string
to uppercase, turning "word" into "WORD"?
>>> text = "this"
>>> answer = ""
>>> for letter in text:
... answer = answer + chr( ord(letter) - 32 )
...
>>> answer
'THIS'
or
>>> text.upper()
'THIS'
2. Can you do that to the first letter of
a word, changing "this" to "This" ?
>>> text = 'this'
>>> chr(ord(text[0]) - 32) + text[1:]
or
>>> text.title()
3. Can you reverse a word, changing
"hello" to "olleh" ?
The trick is to append the new letters
to the left side as we grow the answer.
>>> text = 'this'
>>> answer = ""
>>> for letter in text:
... answer = letter + answer
...
There are functions built into python (and the string module)
that can do these things ... or help with them.
Or you can do them yourself with loops, the accumulator pattern,
ord(), and chr() ...
text formatting
Making the output look nice.
There are several ways to do this within python:
the old way (in your text), and the new way (recommended).
In both cases, markers are put within a string to
indicate where values should go, and then variables
are "interpolated" into the string in some given
format. The details get messy.
the old way : ("x=%f" % 3)
I'll mention this and then (mostly) ignore it.
print "Compare %f and %0.20f \n" % (3.14, 3.14)
Here the "%" symbol is placed between (a) the string with its markers
and (b) a sequence of the values to be interpolated.
The funky symbols within the string (%i, %f, %d, %s) give the format (integer, float, decimal, string).
the new way : "x={}".format(3)
The python language has been transitioning to a new syntax
for string formatting, the .format() string method and {}
for interpoloation.
The new version looks like this :
print "Compare {} and {:0.20} ".format(3.14, 3.14)
This is what you should do. For the details see the docs.
Files
A 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")
# In that last line :
# '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") # \n is newline
summary of strings, text, files
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
in class 1 : all of us code together a program to do file conversion for rot13
- 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
Are we having fun yet?
in class 2 : all of us code together in class a program that counts the characters in a file.
- Discuss where to start ...
Finally, depending on time, discuss "decoder ring" stuff,
translating words into codes by adding an offset.
- We can get the number for (say) 'a' with ord('a')
- We can add an offset to the number, wrapping around at 'z' with the "i % 26" mod arithmetic operator.
- And then translate from numbers back to letters with chr()
- Do this letter by letter, accumulating the result.
- The code is something like this : cipher.py .
The assignment for next week has lots of practice with this sort of stuff ...