Format and pythonformat
Usage:
It uses {} And: to replace the traditional % method.
1. Use location parameters
Key point: The following example shows that the location parameter is not subject to the order and can be {}. As long as there is a corresponding parameter value in the format, the parameter index is enabled from 0, input location parameter list available * List
>>> li = ['hoho',18]>>> 'my name is {} ,age {}'.format('hoho',18)'my name is hoho ,age 18'>>> 'my name is {1} ,age {0}'.format(10,'hoho')'my name is hoho ,age 10'>>> 'my name is {1} ,age {0} {1}'.format(10,'hoho')'my name is hoho ,age 10 hoho'>>> 'my name is {} ,age {}'.format(*li)'my name is hoho ,age 18'
2. Use keyword Parameters
Key point: the keyword parameter value must be correct. You can use a dictionary. When the keyword parameter is passed in, add ** before the dictionary.
>>> hash = {'name':'hoho','age':18}>>> 'my name is {name},age is {age}'.format(name='hoho',age=19)'my name is hoho,age is 19'>>> 'my name is {name},age is {age}'.format(**hash)'my name is hoho,age is 18'
3. Filling and formatting
: [Fill character] [Alignment mode <^>] [width]
>>> '{0: *> 10 }'. format (10) # right alignment '********* 10'> '{0: * <10 }'. format (10) # align left '10 ********* '>' {0: * ^ 10 }'. format (10) # center alignment '***** 10 ****'
4. Precision and hexadecimal
>>> '{0 :. 2f }'. format (1/3) '0. 33 '>>>' {0: B }'. format (10) # binary '000000' >>> '{0: o }'. format (10) # '12' >>> '{0: x }'. format (10) # hexadecimal 'A' >>> '{:,}'. format (12369132698) # format '123' in kilobytes'
5. Use Indexes
>>> li['hoho', 18]>>> 'name is {0[0]} age is {0[1]}'.format(li)'name is hoho age is 18