Review, Formatting Silly Sentences
June 14, 2011 4 Comments
Voice Over Well it’s a straight fight here at Leicester…On the left of the Returning Officer (camera shoes grey-suited man) you can see Arthur Smith, the Sensible candidate and his agent, (camera pans to silly people) and on the other side is the silly candidate Jethro Walrustitty with his agent and his wife.
Officer Here is the result for Leicester. Arthur J. Smith…
Voice Over Sensible Party
Jethro Q. Walrustitty…
Voice Over Silly Party
We have been covering lots of new concepts very quickly. So now is the time to slow down a bit and go over some of the things we’ve already done, to have a look at them in a little more depth. In particular I want to try to give you some direction on how to make these code samples your own.
I also noticed that I did some things in the last tute which we haven’t encountered yet. In particular, I:
- assigned a function to an object r = random.randint. Isn’t Python neat? You can make these assignments, then the name r points at the function random.randint, so you can use r wherever you use the function. Sometimes you can use this pattern to make your program run faster (honest!). However, it might be confusing so I’ll stop it now!
- used tab characters to format a print out: ‘\t’. There are some “control” characters which modify the usual output of a set of printed characters. Of particular interest are ‘\n’ (which makes a new line) and ‘\t’ which adds a tab space. Try printing some strings with \n and \t in them to see what they do.
In this tutorial we’re going to look at formatting strings. In the previous tute we constructed a string by adding (using the ‘+’ operator) them together. Building strings this way can be a little challenging. Another way to do it, is to use formatting strings. We put place markers into a string, and match the place markers with values to go in there. The place markers are identfied by a % sign in the string, and values are added at the end after a % sign. Here is a simple example:
>>> print '%s'%'hi' hi
The string ‘hi’ is inserted in place of the %s (%s (the s is important – not just the % by itself) says insert a string here). There are a number of different options for formatting other than %s (eg %f) but we’re not going into them here. Read the documentation for more details.
>>> print '->%s<-'%'This is the value which is inserted' ->This is the value which is inserted<-
We can define the format string and the value differently:
>>> formatString="...tell that to the young people of today, and %s." >>> print formatString%"they won't believe you" ...tell that to the young people of today, and they won't believe you.
Then you can use the same format string with a different value. This is useful when you have to print something repetitive, where only a part of it changes:
>>> print formatString%"they will fall about laughing" ...tell that to the young people of today, and they will fall about laughing.
You can put multiple values into the format string, but the values you supply must:
- be in brackets () (this makes a thing called a tuple, but we haven’t seen them yet); and
- have a comma between each of the values; and
- there must be the same number of values as there are %s in the format string.
So, in the previous tute, we might have done something like this: >>> formatString="%s x %s = %s" >>> print formatString%(2,2,4) 2 x 2 = 4
We can also pass variables to be printed as values to the formatting string:
>>> i=2 >>> j=3 >>> print formatString%(i,j,i*j) 2 x 3 = 6
So here’s the times table again:
>>> for i in range(12): ... for j in range(12): ... print formatString%(i+1,j+1,(i+1)*(j+1))
Let’s adapt the silly sentence example from last tutorial.
1. open your text editor,
2. open a new file
3. “save as” this empty file with the name “sillySentences110614.py”, save it in the p4k directory we’ve created to hold our stuff.
Now copy and paste this:
import random nouns = ["apple","toy car","pumpernickel","dinner","pillow","homework","little finger","house","pencil","letterbox","hamster"] verbs = ["ate","played","smelled","lost","forgot","dropped","hid","erased","infuriated","planted","ripped up","tripped over","dusted","talked to"] v = len(verbs)-1 n = len(nouns)-1 numberOfSillySentences = 10 formatString = "I was very taken aback when Mrs Pepperpot %s my %s." for i in range(numberOfSillySentences): verb = verbs[random.randint(0,v)] noun = nouns[random.randint(0,n)] print formatString%(verb,noun)
And save the file. Can you see how much easier it is to get the spacing right?
Run the file by going to a console and typing:
> python sillySentences110614.py
Now you need to make this code your own.
Exercise: First, change some of the verbs and nouns. You will see the pattern – for verbs you need to substitute doing words, and they need to be in the past – ate rather than eat. For nouns you need to substitute words which name things. Save the file, then run the program again from the console with:
> python sillySentences110614.py
Next, we’re going to change it to add some feelings in, but you have to supply the feelings:
Exercise: add some feeling words to the feelings arrray and run again:
import random nouns = ["apple","toy car","pumpernickel","dinner","pillow","homework","little finger","house","pencil","letterbox","hamster"] verbs = ["ate","played","smelled","lost","forgot","dropped","hid","erased","infuriated","planted","ripped up","tripped over","dusted","talked to"] feelings=["very taken aback","very happy","quite sad"] # add more feelings to the array here v = len(verbs)-1 n = len(nouns)-1 f = len(feelings)-1 numberOfSillySentences = 10 formatString = "I was %s when Mrs Pepperpot %s my %s." for i in range(numberOfSillySentences): verb = verbs[random.randint(0,v)] # choose a verb,noun, feeling by calculating a random integer noun = nouns[random.randint(0,n)] # between 0 and v,n,f (number of verbs,nouns, feelings) feeling = feelings[random.randint(0,f)] print formatString%(feeling,verb,noun) # substitute into the format string and print