04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

56 CHAPTER 3 ■ WORKING WITH STRINGS<br />

In the material that follows, I walk you through the various parts of the conversion specifier.<br />

For a summary, see the sidebar “Conversion Specifier Anatomy.”<br />

CONVERSION SPECIFIER ANATOMY<br />

A basic conversion specifier (as opposed to a full conversion specifier, which may contain a mapping key as<br />

well; see Chapter 4 for more information) consists of the items that follow. Note here that the order is crucial.<br />

• The % character. This marks the beginning of the conversion specifier.<br />

• Conversion flags (optional). These may be either -, indicating left alignment; +, indicating that a sign<br />

should precede the converted value; “ ” (a space character), indicating that a space should precede<br />

positive numbers; or 0, indicating that the conversion should be zero-padded.<br />

• The minimum field width (optional). The converted string will be at least this wide. If this is an *<br />

(asterisk), the width will be read from the value tuple.<br />

• A . (dot) followed by the precision (optional). If a real number is converted, this many decimals should<br />

be shown. If a string is converted, this number is that maximum field width. If this is an * (asterisk), the<br />

precision will be read from the value tuple.<br />

• The conversion type (see Table 3-1).<br />

Simple Conversion<br />

The simple conversion, with only a conversion type, is really easy to use:<br />

>>> 'Price of eggs: $%d' % 42<br />

'Price of eggs: $42'<br />

>>> 'Hexadecimal price of eggs: %x' % 42<br />

'Hexadecimal price of eggs: 2a'<br />

>>> from math import pi<br />

>>> 'Pi: %f...' % pi<br />

'Pi: 3.141593...'<br />

>>> 'Very inexact estimate of pi: %i' % pi<br />

'Very inexact estimate of pi: 3'<br />

>>> 'Using str: %s' % 42L<br />

'Using str: 42'<br />

>>> 'Using repr: %r' % 42L<br />

'Using repr: 42L'<br />

For a list of all conversion types, see Table 3-1.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!