In this conclusion to a three-part series on Python 3.1, you'll learn how to format strings and put them together in different ways. We'll also review what we covered in the series as a whole, which includes your first Python program. This article is excerpted from the book Beginning Python: Using Python 2.6 and Python 3.1,, written by James Payne, Developer Shed Editor-in-Chief (Wrox, 2010; ISBN: 0470414634).
In this example, you tell the format specifier how many characters to expect. Try the following code and watch what happens:
> > > “%s %s %10s” % (“John” , “Every”, “Man”)
‘John Every Man’
> > > “%-5s %s %10s” % (“John” , “Every”, “Man”)
John Every Man
How It Works
In the first line of code, the word Man appears far away from the other words; this is because in your last format specifier, you added a 10, so it is expecting a string with ten characters. When it does not find ten (it only finds three . . . M - a - n) it pads space in between with seven spaces.
In the second line of code you entered, you will notice that the word Every is spaced differently. This occurs for the same reason as before — only this time, it occurred to the left, instead of the right.
Whenever you right a negative ( – ) in your format specifier, the format occurs to the left of the word. If there is just a number with no negative, it occurs to the right.