Home » Python » Python notes the string format

Python notes the string format

There are two ways to format strings in

Python:

1. string formatted expressions, similar to the printf model in the C language;

2. string formatting method call, format method.


String formatted expression: '%' ()

formatting rules: %[(name)][flags][width][.precision]typecode


name: dictionary key
flags: left justified (-), plus sign (+), and zero padding (0)
width: bit
.precision: decimal point

width and precision can be encoded as one *, enabling dynamic control of


'this, is,%d,%s, bird',% (1, 'dead')
>>>, , "%f,%.2f,%.*f", % (1/3.0, 1/3.0, 4, 1/3.0)
'0.333333, 0.33, 0.3333'
# dictionary based string formatting, reference dictionary key to extract the corresponding value
>>>, ,% (n), D (x), s, , {, , 1, , x, , , apple, N, }
'1 apple'
# is better with vars ():)

String formatting call method: format
The

format is used as a placeholder by location or keyword indicating the target to be replaced and the parameters to be inserted,.


>>>, '{0}, {1}, ans, {2}'.format ('aaa', [1, 2, 3], 123)
'aaa, [1, 2, 3], ans, 123'
'{0} {month} ans {food}'.format > > >, ('egg', month=3, food=[1, 2])
'egg, 3, ans, [1, 2]'

The more advanced use of

: referencing attributes of objects by location or keywords


>>> import sys
>>>, 'my, {1[keyname]}, run, {0.platform}'.format (sys, {'keyname': 'laptop'})
'my laptop run win32'
>>>, 'my, {config[keyname]}, runs, {sys.platform}'.format (sys=sys, config={'keyname': 'laptop'})
'my laptop runs win32'
# can also specify indexes for lists (or other sequences) to be offset by
>>>, 'first={0[0]}, third={0[2]}, last={1[1]}'.format ([11, 22, 33], , use, )
'first=11, third=33, last=s'

more specific formatting:

After the identity of the replacement object, a colon is used, followed by a formatted declaration that specifies the field size, alignment, etc., and its formal structure is as follows:

{fieldname! Convertionflag: formatspec}

* fieldname: identifies a number or keyword
that replaces an object
* conversionflag: you can call r, s, a, repr, STR, and ascii functions on that value.

* formatspec: Specifies the width, alignment, zero padding, decimal point precision


The

formatspec composition is described as follows:

[[fill]align][sign][#][0][width][, precision][typecode],

align: Yes, <, >, ^, left justified, right justified, centered, aligned,

#: display 0x or 0X
before octal number, 0, sixteen decimal number
0: fill 0 instead of space

precision: decimal point

typecode:o, x, D, b, octal, sixteen, decimal, binary...


>>>, '{0:<5}|{1:>5}|{2:^5}'.format (123, 123, 123)
'123 123| 123' |
'{0:e} {1:.3e}, {2:g}'.format > > >, (math.pi, math.pi, math.pi)
'3.141593e+00, 3.142e+00, 3.14159'
{0:o}, {0:b}, '{0:x}., {0:d}'.format (255)
'ff, 377, 11111111, 255'
'{0:.{1}f}'.format (1/3, 5).
'0.33333'
> > > '{! S}, r}, a}'.format {{!! (333, 444, 555)
'333, 444, 555'
'{0:#10x}'.format (15).
'0xf'

Latest