Python USES the format function to format the use of strings

  • 2020-05-07 19:57:40
  • OfStack

Since python 2.6, a new function str.format () for formatting strings has been added, which is 10 times more powerful. So, how does it compare to the previous % format string? Let us lift the veil of its coyness.
grammar

It replaces % with {} and:.
The "mapping" example

passes through the location


In [1]: '{0},{1}'.format('kzc',18) 
Out[1]: 'kzc,18' 
In [2]: '{},{}'.format('kzc',18) 
Out[2]: 'kzc,18' 
In [3]: '{1},{0},{1}'.format('kzc',18) 
Out[3]: '18,kzc,18'

The format function of the string can accept as many arguments as you like, the positions can be in any order, they can not be used or used more than once, but 2.6 cannot be null {} and 2.7 can.
takes the keyword parameter


In [5]: '{name},{age}'.format(age=18,name='kzc') 
Out[5]: 'kzc,18'

through the object property


class Person: 
  def __init__(self,name,age): 
    self.name,self.age = name,age 
    def __str__(self): 
      return 'This guy is {self.name},is {self.age} old'.format(self=self) 


In [2]: str(Person('kzc',18)) 
Out[2]: 'This guy is kzc,is 18 old'

passes the index


In [7]: p=['kzc',18]
In [8]: '{0[0]},{0[1]}'.format(p)
Out[8]: 'kzc,18'

With these handy "mapping" methods, we have a handy tool. Basic python knowledge tells us that list and tuple can be "broken" into normal argument giving functions, while dict can be broken into keyword argument giving functions (through and *). So you can easily pass list/tuple/dict to format. Very flexible.
format qualifier

It has rich "format qualifiers" (the syntax is {} with:), such as:

fill with alignment
padding is often used in conjunction with alignment 1
^, < , > Center, left, right, and back with width
: characters with padding after the number can only be 1 character. If not specified, the default is to fill with space
Such as


In [15]: '{:>8}'.format('189')
Out[15]: '   189'
In [16]: '{:0>8}'.format('189')
Out[16]: '00000189'
In [17]: '{:a>8}'.format('189')
Out[17]: 'aaaaa189'

precision and type f
precision is often used with type f1


In [44]: '{:.2f}'.format(321.33345)
Out[44]: '321.33'

Where.2 represents the precision with length 2 and f represents the float type.

other types
is mainly base system, b, d, o and x are respectively base 2, base 10, base 8 and base 106.


In [54]: '{:b}'.format(17)
Out[54]: '10001'
In [55]: '{:d}'.format(17)
Out[55]: '17'
In [56]: '{:o}'.format(17)
Out[56]: '21'
In [57]: '{:x}'.format(17)
Out[57]: '11'

Yes, it can also be used as a thousand separator.


In [47]: '{:,}'.format(1234567890)
Out[47]: '1,234,567,890'


Related articles: