84
❘
CHAPTER 5
InteractIng wIth StructureS and ObjectS
In many cases, you need to provide input that doesn’t translate into a string. For example, you
might need to provide integer input for some strings. The interpreter won’t automatically perform
a conversion in this case so you need to perform the task manually. The
conversion symbol is the
exclamation mark (
!
) and the most common conversion is string (
s
). You can also call the
repr()
conversion function by using
r
in place of
s
. Here’s an example of a conversion:
MyString = ‘{0!s} + {1!s} = {2!s}‘
MyString.format(1, 2, 1+2)
In this case, you get an output of ‘1 + 2 = 3’. Notice that this example places the math directly in the
format string. You could place the output of a function there as well.
So far, the examples haven’t done much formatting — they have simply replaced field values with infor-
mation found in other sources. The format operator is the colon (
:
) and
you can combine it with the
conversion operator if you want. To see how this works, think about displaying the previous example in
hexadecimal format. In that case, your code might look like this:
MyString = ‘{0:X} + {1:X} = {2:X}‘
MyString.format(10, 20, 10+20)
The output from this code is in hexadecimal format — you’d see ‘A + 14 = 1E’. Of course, you might
want all the values to take up the same space. In this case, you can tell the interpreter to add some
space to the output using the following string:
MyString = ‘{0:0=4X} + {1:0=4X} = {2:0=4X}‘
This string outputs numbers with zeros as padding. The padding appears after any sign information.
In addition, each of the entries is four digits long. Consequently, the output now looks like this: ‘000A
+ 0014 = 001E’. The formatting has specific entries, all of which are options. It looks like this:
[[fill]align][sign][#][0][width][.precision][type]
Fill characters determine what appears as part of the padding the interpreter uses when you specify
a width, and the field value doesn’t fill the entire space. The
default padding is the space, but you
can specify any character other than the closing brace, which would end the formatting definition.
When you specify a fill character, such as the 0 used in the previous example, you must also use one
of the alignment characters found in Table 5-1.
Do'stlaringiz bilan baham: