The string format '{}' of [python] is used in combination with. Format

String formatting usage: use '{}' and. format() instead of the traditional% method

-1. Use location parameter: the location parameter is not constrained by order, and can be {}. As long as there is a corresponding parameter value in format, the parameter index is from 0, and the incoming location parameter list can be * list

1.1 direct one-to-one correspondence of incoming values

>>> data = ['jack',25]
>>> 'my name is {} ,age {}'.format(data[0],data[1])
'my name is jack ,age 25'

1.2 if the location can be passed in, the order of incoming data will be changed

>>> 'my name is {1} ,age {0}'.format(data[0],data[1])
'my name is 25 ,age jack'

1.3 position value can be passed in multiple times

>>> 'my name is {1} ,age {0}{1}'.format(data[0],data[1])
'my name is 25 ,age jack25'

1.4 no mixed transfer

>>> 'my name is {1} ,age {}'.format(data[0],data[1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot switch from manual field specification to automatic field numbering

1.5 variable parameters can be passed in

>>> 'my name is {1} ,age {0}'.format(*data)
'my name is 25 ,age jack'
>>> 'my name is {} ,age {}'.format(*data)
'my name is jack ,age 25'

-2. Use key parameter: the key parameter value should be correct. You can use the dictionary as the key parameter input value and add * * before the dictionary

2.1 you can use the dictionary as the key parameter input value, and add * * before the dictionary

>>> data2 = {'name':'bruce','age':25}
>>> data2
{'name': 'bruce', 'age': 25}
>>> 'my name is {} ,age {}'.format(**data2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> 'my name is {name} ,age {age}'.format(**data2)
'my name is bruce ,age 25

2.2 one by one correspondence of key parameters

>>> 'my name is {name} ,age {age}'.format(name = 'brcue',age=18)
'my name is brcue ,age 18'

-3. Fill and format:: [fill character] [alignment < ^ >] [width]

>>> '{:*>10}'.format(10)  ##Right alignment
'********10'
>>> '{:*<10}'.format(10)  ##Left alignment
'10********'
>>> '{:*^10}'.format(10)  ##Center alignment
'****10****'

-4. Precision and base

>>> '{:.2f}'.format(1/3)
'0.33'
>>> '{:b}'.format(10)    #Binary system
'1010'
>>> '{:o}'.format(10)     #Octal number system
'12'
>>> '{:x}'.format(10)     #16 binary system
'a'
>>> '{:,}'.format(12369132698)  #Kilo format
'12,369,132,698'

-5. Use index

>>> data
['jack', 25]
>>> 'my name is {0[0]} ,age {0[1]}'.format(data)
'my name is jack ,age 25'

Posted by veeraa2003 on Thu, 02 Apr 2020 01:20:55 -0700