16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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 Ana<strong>to</strong>my.”<br />

CONVERSION SPECIFIER ANATOMY<br />

A basic conversion specifier (as opposed <strong>to</strong> 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 <strong>to</strong> 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!