Online Book Reader

Home Category

Learning Python - Mark Lutz [120]

By Root 1805 0
# Other to/from binary

('0b11111111', 255, 255)

>>> hex(255), int('FF', 16), 0xFF # Other to/from hex

('0xff', 255, 255)

>>> oct(255), int('377', 8), 0o377, 0377 # Other to/from octal

('0377', 255, 255, 255) # 0377 works in 2.6, not 3.0!

Formatting parameters can either be hardcoded in format strings or taken from the arguments list dynamically by nested format syntax, much like the star syntax in formatting expressions:

>>> '{0:.2f}'.format(1 / 3.0) # Parameters hardcoded

'0.33'

>>> '%.2f' % (1 / 3.0)

'0.33'

>>> '{0:.{1}f}'.format(1 / 3.0, 4) # Take value from arguments

'0.3333'

>>> '%.*f' % (4, 1 / 3.0) # Ditto for expression

'0.3333'

Finally, Python 2.6 and 3.0 also provide a new built-in format function, which can be used to format a single item. It’s a more concise alternative to the string format method, and is roughly similar to formatting a single item with the % formatting expression:

>>> '{0:.2f}'.format(1.2345) # String method

'1.23'

>>> format(1.2345, '.2f') # Built-in function

'1.23'

>>> '%.2f' % 1.2345 # Expression

'1.23'

Technically, the format built-in runs the subject object’s __format__ method, which the str.format method does internally for each formatted item. It’s still more verbose than the original % expression’s equivalent, though—which leads us to the next section.

Comparison to the % Formatting Expression

If you study the prior sections closely, you’ll probably notice that at least for positional references and dictionary keys, the string format method looks very much like the % formatting expression, especially in advanced use with type codes and extra formatting syntax. In fact, in common use cases formatting expressions may be easier to code than formatting method calls, especially when using the generic %s print-string substitution target:

print('%s=%s' % ('spam', 42)) # 2.X+ format expression

print('{0}={1}'.format('spam', 42)) # 3.0 (and 2.6) format method

As we’ll see in a moment, though, more complex formatting tends to be a draw in terms of complexity (difficult tasks are generally difficult, regardless of approach), and some see the formatting method as largely redundant.

On the other hand, the formatting method also offers a few potential advantages. For example, the original % expression can’t handle keywords, attribute references, and binary type codes, although dictionary key references in % format strings can often achieve similar goals. To see how the two techniques overlap, compare the following % expressions to the equivalent format method calls shown earlier:

# The basics: with % instead of format()

>>> template = '%s, %s, %s'

>>> template % ('spam', 'ham', 'eggs') # By position

'spam, ham, eggs'

>>> template = '%(motto)s, %(pork)s and %(food)s'

>>> template % dict(motto='spam', pork='ham', food='eggs') # By key

'spam, ham and eggs'

>>> '%s, %s and %s' % (3.14, 42, [1, 2]) # Arbitrary types

'3.14, 42 and [1, 2]'

# Adding keys, attributes, and offsets

>>> 'My %(spam)s runs %(platform)s' % {'spam': 'laptop', 'platform': sys.platform}

'My laptop runs win32'

>>> 'My %(spam)s runs %(platform)s' % dict(spam='laptop', platform=sys.platform)

'My laptop runs win32'

>>> somelist = list('SPAM')

>>> parts = somelist[0], somelist[-1], somelist[1:3]

>>> 'first=%s, last=%s, middle=%s' % parts

"first=S, last=M, middle=['P', 'A']"

When more complex formatting is applied the two techniques approach parity in terms of complexity, although if you compare the following with the format method call equivalents listed earlier you’ll again find that the % expressions tend to be a bit simpler and more concise:

# Adding specific formatting

>>> '%-10s = %10s' % ('spam', 123.4567)

'spam = 123.4567'

>>> '%10s = %-10s' % ('spam', 123.4567)

' spam = 123.4567 '

>>> '%(plat)10s = %(item)-10s' % dict(plat=sys.platform, item='laptop')

' win32 = laptop '

# Floating-point numbers

>>> '%e, %.3e, %g' % (3.14159, 3.14159, 3.14159)

'3.141590e+00, 3.142e+00, 3.14159'

>>> '%f, %.2f, %06.2f' % (3.14159, 3.14159,

Return Main Page Previous Page Next Page

®Online Book Reader