4.4 Results and discussions
4.4.2 Cooling rate effect
The second version of formatting combines items from a set of specified entities/objects to form a formatted string. The entities can be numbers, strings, tuples, lists, dictionarys or their mix. They can be present in the formatted string in toto or in specified/selected parts rearranged in a desired order. The formatting structure is shown in Fig.8.5. The following regarding the formatting are noteworthy here:
In general the formatted string—strg in strg.format(….) —is composed of literal character sets and‘replacement fields’ in a sequence. Each replacement field is enclosed within curly brackets as { }. It specifies an item to be identified from the arguments specified within the method strg.format(…) and how the same is to be structured and merged into the formatted string. The specification is broadly composed of three parts each being optional:
1. The field name is an integer (from 0 onwards) which stands for the serial number of the entity from which the information is to be taken. If the data/information is within the entity its location/identifier may be specified after
182 8 Operations with Files
a dot—‘.’—(in case the entity is a dictionary item, the field name is the key of the entity concerned). If the replacementfields are specified in the same order as the sequence of entities within the brackets, the serial number can be omitted;
the interpreter will assume them to be 0, 1, 2,… and so on, in the same order.
2. The character—‘!’—identifies the conversion field, if the same is present. Three forms of conversions—specified as ‘!s’, ‘!r’, and ‘!a’ are possible. With ee as the specified item, these return str(ee), repr(ee), and ascii(ee) respectively.
3. The character ‘:’ specifies the format specification if the same is present. The format specification here is again composed of a number of optional fields:
Formatted string.format( Source/s)
Dictionary {‘k1’:a1,‘k2’:a2,. . . . ‘kk’:ak}
Tuple ‘a1, a2, . . . . ak’
Single string ‘aa’
Number
Combination of the above – arbitrary order Signifies format method
‘xx. . ..xx F1 xx. . ..xx F2 xx. . . . ..xx Fk xx….xx’
Literal character sets
Fields to be replaced from source – as many numbers as desired
Fi { field name ! Conversion : format_spec } ith field
Mandatory curly bracket – signifies end of field Mandatory curly bracket – signifies beginning of field
fill align sign # 0 width , .precision type
String: identified by ‘s’
Integer: Table 8.6
Floating point / decimal number No. of digits after decimal point – only with floating point / decimal numbers
No. of spaces allocated for the number Do sign-aware zero padding of number Signifies number formatting Option for numbers: Table 8.5 Table 8.4
Character to be used for filling if ‘align’ is specified
Comma as thousand separator All fields optional
Signifies start of format_spec field Three options:
‘!r’ repr(); ‘!s’ str(); ‘!a’ ascii()
Signifies start of conversion field Name of object to be formatted All three fields optional
Fig. 8.5 Details of string formation for printing—Version II
a. The item may be specified as a number, a character, or a string.
b. The width—in the width field—is an integer specifying the number of spaces allocated to the item. If the same is omitted the Interpreter will automatically allot the minimum space width demanded of the item. If the actual width is less than what is allocated, the additional spaces will befilled as specified in thefields—‘fill and align’.
c. ‘fill’ represents any character which can be used to fill the free space.
d. ‘align’ symbol is present only if the filling is called for. There are four possibilities as shown in Table8.4.
e. The option—‘#’—signifies that the item being formatted is a number.
Further the number type offersflexibility in terms of additional fields:
i. The signfield has three options as given in Table8.5.
ii. In case the number is an integer the representations possible are as given in Table8.6. Note that the ‘c’ option implicitly assumes the given integer to be the Unicode value of the character concerned.
iii. The options available for thefloating point numbers are in Table8.7.
Here ‘width’ represents the total width (as the number of spaces) allocated for the number inclusive of the sign and the decimal point.
The illustrative examples formatted conforming to Version I in Fig.8.4 are formatted conforming to Version II and presented in the Python Interpreter sequence in Fig.8.6. The print out of numbers inaz [1], the sequence formed from the dictionary rm [2] and the different representations of the number ab [3]
can be seen to be the same as their counterparts in Fig.8.4.z1 [4] is a tuple of two elements—a single character string—‘h’—and the integer—123 (with ASCII value‘{‘). It has been formatted in [5] with 0[0] and 0[1] specifying the arguments in replacementfield. Here z1 is a single entity being formatted. In [6]—‘h’ and 123
—are two successive entities being formatted—identified through indices 0 and 1 respectively. [7] uses the starred version ofz1 the entities being identified again through indices 0 and 1 respectively.
Table 8.4 Alignment options—formatting Version II Option Meaning
‘<’ Forcesfield to be left-aligned within available space (default for most objects)
‘>’ Forcesfield to be right-aligned within available space (default for numbers)
‘=’ Forces padding to be placed after sign (if any) but before digits—used for printing fields in the form ‘+000000120’—only for numeric types
‘^’ Forcesfield to be centered within available space
Table 8.5 Sign options—formatting Version II Option Meaning
‘+’ Indicates that a sign should be used for both positive as well as negative numbers
‘−’ Indicates that a sign should be used only for negative numbers (default behavior) Space Indicates that a leading space should be used on positive numbers, and a minus sign
on negative numbers
184 8 Operations with Files
The formatting examples in Fig.8.7illustrate the variety andflexibility possible when formatting with Version II. The set of simple strings in the listaz [1] are directly formatted into a string in [2]. The desired replacement order being the same as inaz, the index values are not specified. ay in [3] is a dictionary of four items. They are formatted into a string [4] by specifying the keys in the Table 8.6 Details of integer presentation types—formatting Version II
Type Meaning
‘b’ Binary format—outputs number in base 2.
‘c’ Character—converts integer to corresponding Unicode character before printing
‘d’ Decimal Integer—outputs number in base 10
‘o’ Octal format—outputs number in base 8
‘x’ Hex format—outputs number in base 16, using lower-case letters for digits above 9
‘X’ Hex format—outputs number in base 16, using upper-case letters for digits above 9
‘n’ Number—same as ‘d’, except that current locale setting is used to insert appropriate number separator characters
None Same as‘d’
Table 8.7 Details of floating point number presentation types—formatting Version II Type Meaning
‘e’ Exponent notation—prints number in scientific notation using letter ‘e’ to indicate exponent; default precision is 6
‘E’ Exponent notation—uses upper case ‘E’ as separator character; otherwise same as ‘e’
‘f’ Fixed point—displays number in fixed-point form; default precision is –6
‘F’ Fixed point—same as ‘f’, but converts nan to NAN and inf to INF
‘g’ General format—for a given precision p ≥ 1, this rounds number to p significant digits and then formats result in eitherfixed-point format or in scientific notation, depending on its magnitude. The precise rules are as follows: suppose that the result formatted with presentation type‘e’ and precision p − 1 would have exponent exp. Then if
−4 ≤ exp < p, the number is formatted with presentation type ‘f’ and precision p− 1 − exp. Otherwise, the number is formatted with presentation type ‘e’ and precision p− 1. In both cases insignificant trailing zeros are removed from the significant, and the decimal point is also removed if there are no remaining digits following it. Positive and negative infinity, positive and negative zero, and nans, are formatted as inf,−inf, 0, −0 and nan respectively, regardless of the precision.
A precision of 0 is treated as equivalent to a precision of 1. The default precision is 6
‘G’ General format. Same as‘g’ except switches to ‘E’ if the number gets too large. The representations of infinity and NAN are uppercased, too
‘n’ Number—same as ‘g’, except that current locale setting is used to insert appropriate number separator characters
‘%’ Percentage—multiplies number by 100 and displays in fixed (‘f’) format, followed by a percent sign
None Similar to‘g’, except that fixed-point notation, when used, has at least one digit past the decimal point. The default precision is as high as needed to represent the particular value. The overall effect is to match the output of str() as altered by other format modifiers
respective replacement fields. In [5] and [6] a dictionary of a single item is specified in different forms but the (intended) formatting is the same. The string
‘Uma’ is specified through its key in [7] in the replacement field. Two arguments
—both dictionarys—are present in [8]; but only one item from the second dictionaryis sought by the formatted string. Four different types of entities are
>>> az = (3, -3.2104, -321.04, 321.04, -3210.401) [1]
>>> while True:
... print('{0[0]:#8.2f}'.format(az)) ... print('{0[1]:=#08.2f}'.format(az)) ... print('{0[2]: #08.2f}'.format(az)) ... print('{0[3]:-#8.2f}'.format(az))
>>> rm = {'Name':'Roshan', 'Subject': 'Maths', 'Marks':
100} [2]
>>> print('{0[Name]} gets in {0[Subject]} {0[Marks]} out of 100'.format(rm))
Roshan gets in Maths 100 out of 100
>>> ab = 91 [3]
>>> while True:
... print('Hex value of ab is {0:8x}'.format(ab)) ... print('Explicit Hex value of ab is
{0:#8x}'.format(ab))
... print('Octal value of ab is {0:8o}'.format(ab)) ... print('Explicit Octal value of ab is
>>> 'cc = {0[0]}, nn = {0[1]:c}'.format(z1) [5]
'cc = h, nn = {'
>>> 'cc = {0}, nn = {1:c}'.format('h',123) [6]
'cc = h, nn = {'
>>> 'cc = {0}, nn = {1:c}'.format(*z1) [7]
'cc = h, nn = {'
>>>
Fig. 8.6 Python Interpreter sequence illustrating string formatting conforming to Version II—the examples are the same as those in the sequence in Fig.8.4
186 8 Operations with Files
>>> az = ['aa', 'bb', 'cc', 'dd'] [1]
>>> 'My name is {0[nn]}'.format(dict(nn='Pad')) [5]
'My name is Pad'
>>> 'My name is {0[nn]}'.format({'nn':'Pad'}) [6]
'My name is Pad'
>>> 'My name is {0[nm]}'.format({'nn':'Pad','nm':'Uma'})[7]
'My name is Uma'
>>> 'My name is {1[aa]}'.format({'nn':'Pad', 'nm':'Uma'},
{'ab':'Ravi','aa':'Chandra'}) [8]
'My name is Chandra'
>>> it1 = 34 [9]
>>> it2 = (43.5, 'Swapnam') [10]
>>> it3 = [34.98, it1/it2[0], 'Sat', 'Amritam'] [11]
>>> it4 = {'r1':'Ganga', 'r2':'Yamuna', 'r3':'Krishna',
'r4':'Sindhu'} [12]
>>> ss1 =
'aa:{0},bb:{2[1]},cc:{2[2]},dd:{3[r3]}'.format(it1,it2,it3,
it4) [13]
>>> ss1
'aa : 34, bb : 0.7816091954022989, cc : Sat, dd : Krishna'
>>> import math [14]
>>> print(math.pi) [15]
3.141592653589793
>>> 'v1 = {0}, v2 = {0!s}, v3 = {0!r}'.format(math.pi)[16]
'v1 = 3.141592653589793, v2 = 3.141592653589793, v3 = 3.141592653589793'
>>> 'A value of pi is: {0.pi!s}; but a workable appx. value
is: {0.pi:8.5f}'.format(math) [17]
'A value of pi is: 3.141592653589793; but a workable appx.
value is: 3.14159'
>>> from demo_5 import marks1 [18]
>>> while True: [19]
... print(*marks1.dtb, sep = '\t')
... for jj in marks1.ss:print(*jj, sep = '\t') ... break
...
Name Phy. Chem. Math. Mechn. Engl. [20]
Kishor 75 66 91 87 76
Sanjay 81 62 95 91 62
Siva 41 51 45 39 52
Asha 88 78 97 83 72
Nisha 50 61 68 40 81
Fig. 8.7 Python Interpreter sequence illustrating the variety and flexibility in formatting possible with Version II
formed in [9], [10], [11], and [12]—a number, a string of two different types of items, a list of different types of items including one involving computation of an algebraic expression and the last one being a dictionary. All these form arguments for formingss1—the formatted string in [13]. The replacement fields to formss1 are also in different orders.
The math module is imported [14] and the value ofπ directly printed out in [15].v1, v2, and v3 in the formatted string in [16] represent π in three different ways—all giving identical results. The field width specified for π in [17]—5 digits
—gives a corresponding approximate value of π. pi (π) has been defined as a number in the math module (see‘math.__dict__’); hence it is accessed as math.
pihere.
Example 8.1 Marks earned by a set of students in different subjects are given as a set of strings in ‘demo_5.marks1’ (see Fig.5.16). The subject names and the student names are also given there. Output the data as a well arranged formatted table.
The program to present the information is in the suite from [19]. The output is presented in the lines starting with [20]. The table is properly formatted (spaces uniformly set out and aligned) since the length of every entity in the table is equal to/less than the default tab size (8). If the length of any quantity exceeds this tab size, the program has to be suitably changed.