working with strings in python part2 at codelent
TEMPLATE STRINGS
The string module offers another way of formatting values: template strings. They work more like variable
substitution in many UNIX shells, with $foo being replaced by a keyword argument called foo (for more about
keyword arguments, see Chapter 6), which is passed to the template method substitute:
>>> from string import Template
>>> s = Template('$x, glorious $x!')
>>> s.substitute(x='slurm')
'slurm, glorious slurm!'
If the replacement field is part of a word, the name must be enclosed in braces, in order to clearly indicate
where it ends:
>>> s = Template("It's ${x}tastic!")
>>> s.substitute(x='slurm')
"It's slurmtastic!"
In order to insert a dollar sign, use $$:
>>> s = Template("Make $$ selling $x!")
>>> s.substitute(x='slurm')
'Make $ selling slurm!'
Instead of using keyword arguments, you can supply the value-name pairs in a dictionary (see
Chapter 4):
>>> s = Template('A $thing must never $action.')
>>> d = {}
>>> d['thing'] = 'gentleman'
>>> d['action'] = 'show his socks'
>>> s.substitute(d)
'A gentleman must never show his socks.'
There is also a method called safe_substitute that will not complain about missing values or incorrect
uses of the $ character
String Formatting: The Long Version
The right operand of the formatting operator may be anything; if it is either a tuple or a mapping
(like a dictionary), it is given special treatment. We haven’t looked at mappings (such as
dictionaries) yet, so let’s focus on tuples here. We’ll use mappings in formatting in Chapter 4,
where they’re discussed in greater detail.
If the right operand is a tuple, each of its elements is formatted separately, and you need a
conversion specifier for each of the values.
¦Note If you write the tuple to be converted as part of the conversion expression, you must enclose it in
parentheses to avoid confusing Python:
>>> '%s plus %s equals %s' % (1, 1, 2)
'1 plus 1 equals 2'
>>> '%s plus %s equals %s' % 1, 1, 2 # Lacks parentheses!
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: not enough arguments for format string
A basic conversion specifier (as opposed to a full conversion specifier, which may contain
a mapping key as well; see Chapter 4 for more information) consists of the items that follow.
Note that the order of these items is crucial.
• The % character: This marks the beginning of the conversion specifier.
• Conversion flags: These are optional and may be -, indicating left alignment; +, indicating
that a sign should precede the converted value; “ ” (a space character), indicating
that a space should precede positive numbers; or 0, indicating that the conversion
should be zero-padded.
• The minimum field width: This is also optional and specifies that the converted string will
be at least this wide. If this is an * (asterisk), the width will be read from the value tuple.
• A . (dot) followed by the precision: This is also optional. If a real number is converted,
this many decimals should be shown. If a string is converted, this number is the maximum
field width. If this is an * (asterisk), the precision will be read from the value tuple.
• The conversion type: This can be any of the types listed in Table 3-1.
Conversion Type Meaning
x Unsigned hexadecimal (lowercase)
X Unsigned hexadecimal (uppercase)
e Floating-point exponential format (lowercase)
E Floating-point exponential format (uppercase)
f, F Floating-point decimal format
g Same as e if exponent is greater than –4 or less than precision; f otherwise
G Same as E if exponent is greater than –4 or less than precision; F otherwise
c Single character (accepts an integer or a single character string)
r String (converts any Python object using repr)
s String (converts any Python object using str)
d, i Signed integer decimal
o Unsigned octal
u Unsigned decimal
Simple Conversion
The simple conversion, with only a conversion type, is really easy to use:
>>> 'Price of eggs: $%d' % 42
'Price of eggs: $42'
>>> 'Hexadecimal price of eggs: %x' % 42
'Hexadecimal price of eggs: 2a'
>>> from math import pi
>>> 'Pi: %f...' % pi
'Pi: 3.141593...'
>>> 'Very inexact estimate of pi: %i' % pi
'Very inexact estimate of pi: 3'
>>> 'Using str: %s' % 42L
'Using str: 42'
>>> 'Using repr: %r' % 42L
'Using repr: 42L'
Signs, Alignment, and Zero-Padding
Before the width and precision numbers, you may put a “flag,” which may be either zero, plus,
minus, or blank. A zero means that the number will be zero-padded:
>>> '%010.2f' % pi
'0000003.14'
It’s important to note here that the leading zero in 010 in the preceding code does not
mean that the width specifier is an octal number, as it would in a normal Python number.
When you use 010 as the width specifier, it means that the width should be 10 and that the
number should be zero-padded, not that the width should be 8:
>>> 010
8
A minus sign (-) left-aligns the value:
>>> '%-10.2f' % pi
'3.14 '
As you can see, any extra space is put on the right-hand side of the number.
A blank (“ ”) means that a blank should be put in front of positive numbers. This may be
useful for aligning positive and negative numbers:
>>> print ('% 5d' % 10) + '\n' + ('% 5d' % -10)F
10
-10
Finally, a plus (+) means that a sign (either plus or minus) should precede both positive
and negative numbers (again, useful for aligning):
>>> print ('%+5d' % 10) + '\n' + ('%+5d' % -10)
+10
-10
0 comments:
Post a Comment