Python tutorials :: working with strings - 24loader, Home of exclusive blog and update music and entertaiment

Python tutorials :: working with strings

<
 WORKING WITH STRINGS
>>> '%10.2f' % pi # Field width 10, precision 2
' 3.14'
>>> '%.2f' % pi # Precision 2
'3.14'
>>> '%.5s' % 'Guido van Rossum'
'Guido'
You can use an * (asterisk) as the width or precision (or both). In that case, the number will
be read from the tuple argument:
>>> '%.*s' % (5, 'Guido van Rossum')
'Guido'
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
In the example shown in Listing 3-1, I use the asterisk width specifier to format a table of
fruit prices, where the user enters the total width of the table. Because this information is sup￾plied by the user, I can’t hard-code the field widths in my conversion specifiers. By using the
asterisk, I can have the field width read from the converted tuple.
Listing 3-1. String Formatting Example
# Print a formatted price list with a given width
width = input('Please enter width: ')
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'
format = '%-*s%*.2f'
print '=' * width
print header_format % (item_width, 'Item', price_width, 'Price')
print '-' * width
print format % (item_width, 'Apples', price_width, 0.4)
print format % (item_width, 'Pears', price_width, 0.5)
print format % (item_width, 'Cantaloupes', price_width, 1.92)
print format % (item_width, 'Dried Apricots (16 oz.)', price_width, 8)
print format % (item_width, 'Prunes (4 lbs.)', price_width, 12)
print '=' * width
The following is a sample run of the program:

No comments

Theme images by friztin. Powered by Blogger.
//]]>