Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

7. python string formatting method (2)


May 10, 2021 Python2


Table of contents


7. python string formatting method (2)

This follows the previous section, where we talked about how to add specific formatting

is to specify the size, alignment, and type-specific encoding of the replacement field, as follows:

{fieldname!conversionflag:formatspec}

Fieldname specifies a number or keyword for an argument, followed by an optional .name or reference

Conversionflag can be r/s/a or a call to the repr/str/ascii built-in function on that value

formatspec specifies how the value is represented, such as field broadband, alignment, zeroing, scale accuracy, and so on, and ends with an optional data type encoding

  >>> '{0:10}={1:10}'.format ('abcde',1.234566789)  
  'abcde     =1.234566789'    >>> '{0:10}={1:3}'.format ('abcde',1.234566789)  
  'abcde     =1.234566789'  
  >>> '{0:10}={1:3}'.format ('abcde',123456678.9)  
  'abcde     =123456678.9'  
  >>> '{0:.format ('abcde',123456678.9)  
  'abcde     =123456678.9'    >>> '{0:>10}={1:3}'.format ('abcde',123456678.9)  
  '     abcde=123456678.9'  
  >>> import sys  
  >>> '{0.platform:>10}={1:3}'.format (sys,123456678.9)  
  '     win32=123456678.9'  

Some examples are given above

The parameters of a field that is 10 bytes wide are represented by

The parameters of a left-aligned 10-byte-wide field are represented by the

The parameters of a right-aligned 10-byte-wide field are represented by

The properties of the sys module are read by the s0.platform

Here are some more examples

  >>> '{0:e},{1:.3e},{2:g}'.format (3.141592,3.141592,3.141592)  
  '3.141592e+00,3.142e+00,3.14159'  
  >>> '{0:f},{1:.2f},{2:06.2f}'.format (3.141592,3.141592,3.141592)  
  '3.141592,3.14,003.14'  
  >>>   

The representative of the

Only three-bit scientific counting is reserved for the scientific count of the three-bit

Use g to represent floating points

The floating point of the two-bits is retained by the value of the two-bit

The six-byte section of the .2:06.2f is a string that retains two-bit-less-width complements

In addition to the above hedding system, also supports the octal system, he heteen system

  >>> '{0:X},{1:o},{2:b}'.format (255,255,255)  
  'FF,377,11111111'  
  >>> bin(255),int('11111111',2),0b11111111  
  ('0b11111111'255255)  

It also supports embedding expressions in format for dynamic acquisition

  >>> '{0:f},{1:.2f},{2:06.2f}'.format (1/3,1/3,1/3)  
  '0.333333,0.33,000.33'