3 use string

catalogue

three point three   String formatting: full version

3.3.1 simple conversion

3.3.2 field width and accuracy

3.3.3 symbols, alignment and filling with 0

Listing 3-1 example of string formatting

The next section follows: string methods

three point three   String formatting: full version

The right operand of the format string can be of any type. If it is a tuple or mapping type (such as a dictionary), the string format will be different. We haven't covered mapping (such as dictionaries), so let's take a look at tuples first. The formatting of the map is also described in detail in Chapter 4.

If the right operand is a tuple, each element will be formatted separately, and each value needs a corresponding conversion specifier.

Ps: if the tuple to be converted exists as part of the conversion expression, it must be enclosed in parentheses to avoid errors.

>>> '%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 <module>
TypeError: not enough arguments for format string
>>> '%s plus' % 1, 1, 2 #Lacks parentheses!   #Only the first 1 is identified, and the other 1 and 2 are juxtaposed
('1 plus', 1, 2)

The basic conversion specifier (corresponding to the complete conversion specifier, that is, the specifier including the mapping key, Chapter 4) includes the following parts. Note that the order of these items is crucial.

(1) % character: marks the beginning of the conversion specifier.

(2) Conversion flag (optional): - indicates left alignment+ Indicates that a sign should be added before the conversion value; “  ” (white space character) indicates that a space is reserved before a positive number; 0 indicates that the conversion value is filled with 0 if the number of digits is not enough( See 3.3.3 below)

(3) Minimum field width (optional): the converted String should at least have the width specified by the value. If it is *, the width will be read out from the value tuple( See 3.3.2 below)

(4) Point (.) followed by precision value (optional): if the conversion is a real number, the precision value represents the number of digits after the decimal point. If the conversion is a string, the number represents the maximum field width. If it is *, the precision will be read out from the tuple( See 3.3.2 below)

(5) Conversion type: see table 3-1

Conversion type

meaning

d,i

Signed decimal integer

o

Unsigned octal

u

Unsigned decimal

x

Unsigned hex (lowercase)

X

Unsigned hex (uppercase)

e

Floating point numbers in scientific notation (lower case)

E

Floating point numbers in scientific notation (in uppercase)

f.F

Decimal floating point number

g

If the index is greater than - 4 or less than the precision value, it is the same as e, and the other cases are the same as f

G

If the index is greater than - 4 or less than the precision value, it is the same as E, and other conditions are the same as F

c

Single character (accept integer or single character string)

r

String (use repr to convert any python object) (repr: create a string to represent the value with a legal python expression. Repr is a function and str is a type)

s

String (convert any python object using str)

3.3.1 simple conversion

For simple conversion, you only need to write out the conversion type:  

>>> 'Price of eggs: $%d' % 42   #%d signed decimal
'Price of eggs: $42'
>>> 'Hexadecimal of eggs: %x' % 42   #Unsigned hex
'Hexadecimal of eggs: 2a'
>>> from math import pi     #Introducing math pi module
>>> 'Pi: %f...' % pi    #Decimal floating point number
'Pi: 3.141593...'
>>> 'Very inexact estimate of pi: %i' % pi    #Decimal i, d
'Very inexact estimate of pi: 3'
>>> 'Using str: %s' %42L     #character string
'Using str: 42'
>>> 'Using str: %r' %42L    #String repr function
'Using str: 42L'

3.3.2 field width and accuracy

Conversion specifiers can include field width and precision. Field width is the minimum number of characters retained by the converted value, precision (for numeric conversion) is the number of decimal places that should be included in the result, or (for string conversion) is the maximum number of characters that can be included in the converted value.

Both parameters are integers (first the field width, then the precision), separated by a point number (.). Although both parameters are optional, if only precision is given, the point number must be included:

>>> '%10f' % pi  #Field width 10
'  3.141593'
>>> '%10.2f' % pi  #Field width 10, precision 2
'      3.14'
>>> '%.2f' % pi  #Precision 2
'3.14'
>>> '%.5s' % 'Guido van Rossum'
'Guido'

You can use * (asterisk) as the field width or precision (or both *), and the value will be read out from the tuple parameter:

>>> '%.*s' % (5,'Guido van Rossum')
'Guido'
>>> '%10.*s' % (5,'Guido van Rossum')   #The total field width is 10 and 5 strings are printed
'     Guido'
>>> '%10.*s' % (12,'Guido van Rossum')
'Guido van Ro'  #12 characters, 10 field widths (minimum number of characters) are set, and the accuracy is 12 (maximum number of characters)

3.3.3 symbols, alignment and filling with 0

You can also place a flag before the field width and precision values, which can be zero, plus, minus, or space. Zero means that the number will be filled with 0.

>>> '%010.2f' % pi   #0 indicates the conversion value. If the number of bits is not enough, fill it with 0.
'0000003.14'

Note that the 0 at the beginning of 010 does not mean that the field width specifier is an octal number. It is just an ordinary python value. When 010 is used as the field width specifier, it means that the field width is 10 and 0 is used to fill the empty bits, instead of 8:

>>> 010
8

The minus sign (-) is used to align the values to the left

>>> '%-10.2f' % pi  #As mentioned earlier -: - left alignment
'3.14      '  #Extra space to the right of the number

And blank“  ” Means that a positive number is preceded by a space; this is useful when you need to align positive and negative numbers:

>>> print ('% 5d' %10) + '\n' + ('% 5d' % -10)
   10
  -10

Finally, the plus sign (+) marks both positive and negative numbers (also useful for alignment)  

>>> print ('%+5d' %10) + '\n' + ('%+5d' % -10)
  +10
  -10

Listing 3-1 example of string formatting

[root@mds1 python]# vim  stringFormat.py
#!/usr/bin/python2
#coding=utf-8
#Print the formatted price list with the 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)  #'%-*s%*.2f' % (25,'Apples',10,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
[root@mds1 python]# chmod a+x stringFormat.py 
[root@mds1 python]# ./stringFormat.py 
Please enter width: 35
===================================
Item                          Price
-----------------------------------
Apples                         0.40
Pears                          0.50
Cantaloupes                    1.92
Dried Apricots (16 oz.)        8.00
Prunes (4 lbs.)               12.00
===================================

The next section follows: string methods

Tags: Python data structure linked list

Posted on Wed, 01 Dec 2021 10:08:55 -0500 by MaDSEGA