06A String formatting

A student asks:
> (1) I would like to be able to put some text plus a variable in the
> raw_input string expression, but if I do that, the comma between them
> signals two arguments, whereas raw_input only expects one.
> For example, I have randomly selected a key from my dictionary, and
> named it 'species’; now I want to get the user’s response to this:
> “What is [species] nesting site?” and compare it to a value (nesting
> sites). If I say x = raw_input (“What is”, species,”nesting site?”),
> raw_input doesn’t like that. (I suspect there may be no fix but to
> print the variable in a separate statement.)

raw_input just takes a string, but Python has a great way of
formatting strings using variables ... I've been wanting to work
that into a lesson but haven't quite found the space, so I'm really
glad you asked.

Any time you're using a string, you can add formatting parameters to
it using % signs and a list of the variables. It looks like this:

x = raw_input("What is %s nesting site? " % (species))

Where you would normally put just a plain string, instead you put a
string with % specifiers inside it (called "format specifiers"),
followed by a single %, followed by a tuple containing the variables
to match the format specifiers.

Format specifiers have types: %s means insert a string into the
longer string (so if species = "blue footed booby", it would insert
that string where you put the %s). %d means an integer printed in
decimal format (you can also use %x for hexidecimal, %o for octal
etc.), %f means a floating point number. So you could say

print "There are %d birds at the %s nesting site" % ("booby", 572)

You can also do more complex formatting, like controlling how many
decimal places to show or printing in columns of a specific width.
Here are the gory details:
http://docs.python.org/library/stdtypes.html#string-formatting

> (2) Let’s suppose my keys are questions. I randomly choose one and
> name it 'question’. I would like to use that for my raw_input expression
> (x = raw_input(question)) with a line return at the end, so that the
> user enters her response on the next line, not right on the same line as
> the question. I was trying to use \n in various ways at the end of the
> raw_input statement but could not make it work. Can I get a pointer on
> this?

Probably the easiest way is this:

raw_input(question + '\n')

passing raw_input a string that's your question string with a newline
added on to the end of it. Does that do what you need?