4.2. Formatting strings


All data printed on the screen have to be character data. But values can have different types. Therefore they have to be transformed into strings beforehand. This transformation is handled by the print statement.

It is possible to control this transformation when a specific format is needed. In the examples above, the float value of the gc calculation is written with lots of digits following the dot which are not very significant. The next example shows a more reasonable output:

>>> print "%.3f" % gc
>>> print "%3.1f %%" % (gc*100)
43.2 %
>>> print "the gc percentage of dna: %10s... is: %4.1f %%." % (dna, gc*100)
the gc percentage of dna: ATGCAGTGCA... is: 43.2 %

Figure 4.1 shows how to interpret the example above. The % (modulo) operator can be used to format strings. It is preceded by the formatting template and followed by a comma separated list of values enclosed in parentheses. These values replace the formatting place holders in the template string. A place holder starts with a % followed by some modifiers and a character indicating the type of the value. There has to be the same number of values and place holders.

Figure 4.1. Interpretation of formatting templates


Table 4.1 provides the characters that you can use in the formatting template and Table 4.2 gives the modifiers of the formatting character.


Remember that the type of a formatting result is a string and no more the type of the input value.

>>> "%.1f" % (gc*100) 
>>> res = "%.1f" % (gc*100)
>>> at = 100 - res
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for -: 'int' and 'str'
>>> res

Table 4.1. String formatting: Conversion characters

Formatting characterOutputExampleResult
d,idecimal or long integer"%d" % 10'10'
o,xoctal/hexadecimal integer"%o" % 10'12'
f,e,Enormal, 'E' notation of floating point numbers"%e" % 10.0'1.000000e+01'
sstrings or any object that has a str() method "%s" % [1, 2, 3]'[1, 2, 3]'
rstring, use the repr() function of the object "%r" % [1, 2, 3]'[1, 2, 3]'
%literal %  

Table 4.2. String formatting: Modifiers

name in parenthesesselects the key name in a mapping object"%(num)d %(str)s" % { 'num':1, 'str':'dna'}'1 dna'
-,+left, right alignment"%-10s" % "dna"'dna_______'
0zero filled string"%04i" % 10'0010'
numberminimum field width"%10s" % "dna"'_______dna'
. numberprecision"%4.2f" % 10.1'10.10'