英文原文在这儿:https://pyformat.info/#number_padding Padding numbers
Similar to strings numbers can also be constrained to a specific width.
'%4d' % (42,)
'{:4d}'.format(42)
42
Again similar to truncating strings the precision for floating point numbers limits the number of positions after the decimal point.
For floating points the padding value represents the length of the complete output. In the example below we want our output to have at least 6 characters with 2 after the decimal point.
'%06.2f' % (3.141592653589793,)
'{:06.2f}'.format(3.141592653589793)
003.14
For integer values providing a precision doesn't make much sense and is actually forbidden in the new style (it will result in a ValueError).
'%04d' % (42,)
'{:04d}'.format(42)
0042
Signed numbers
By default only negative numbers are prefixed with a sign. This can be changed of course.
'%+d' % (42,)
'{:+d}'.format(42)
+42
Use a space character to indicate that negative numbers should be prefixed with a minus symbol and a leading space should be used for positive ones.
'% d' % ((- 23),)
'{: d}'.format((- 23))
-23
'% d' % (42,)
'{: d}'.format(42)
42
New style formatting is also able to control the position of the sign symbol relative to the padding.
This operation is not available with old-style formatting.
'{:=5d}'.format((- 23))
- 23
'{:=+5d}'.format(23)
+ 23
Named placeholders
Both formatting styles support named placeholders.
data = {'first': 'Hodor', 'last': 'Hodor!'}
'%(first)s %(last)s' % data
'{first} {last}'.format(**data)
Hodor Hodor!
.format()
also accepts keyword arguments.
This operation is not available with old-style formatting.
'{first} {last}'.format(first='Hodor', last='Hodor!')
Hodor Hodor!
Getitem and Getattr
New style formatting allows even greater flexibility in accessing nested data structures.
It supports accessing containers that support __getitem__
like for example dictionaries and lists:
This operation is not available with old-style formatting.
person = {'first': 'Jean-Luc', 'last': 'Picard'}
'{p[first]} {p[last]}'.format(p=person)
Jean-Luc Picard
data = [4, 8, 15, 16, 23, 42]
'{d[4]} {d[5]}'.format(d=data)
23 42
As well as accessing attributes on objects via getattr()
:
This operation is not available with old-style formatting.
class Plant(object):type = 'tree'
'{p.type}'.format(p=Plant())
tree
Both type of access can be freely mixed and arbitrarily nested:
This operation is not available with old-style formatting.
class Plant(object):type = 'tree'kinds = [{'name': 'oak'}, {'name': 'maple'}]
'{p.type}: {p.kinds[0][name]}'.format(p=Plant())
tree: oak
Datetime
New style formatting also allows objects to control their own rendering. This for example allows datetime objects to be formatted inline:
This operation is not available with old-style formatting.
from datetime import datetime
'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))
2001-02-03 04:05
Parametrized formats
Additionally, new style formatting allows all of the components of the format to be specified dynamically using parametrization. Parametrized formats are nested expressions in braces that can appear anywhere in the parent format after the colon.
Old style formatting also supports some parametrization but is much more limited. Namely it only allows parametrization of the width and precision of the output.
Parametrized alignment and width:
This operation is not available with old-style formatting.
'{:{align}{width}}'.format('test', align='^', width='10')
test
Parametrized precision:
'%.*s = %.*f' % (3, 'Gibberish', 3, 2.7182)
'{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3)
Gib = 2.718
Width and precision:
'%*.*f' % (5, 2, 2.7182)
'{:{width}.{prec}f}'.format(2.7182, width=5, prec=2)
2.72
The nested format can be used to replace any part of the format spec, so the precision example above could be rewritten as:
This operation is not available with old-style formatting.
'{:{prec}} = {:{prec}}'.format('Gibberish', 2.7182, prec='.3')
Gib = 2.72
The components of a date-time can be set separately:
This operation is not available with old-style formatting.
from datetime import datetimedt = datetime(2001, 2, 3, 4, 5)
'{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')
2001-02-03 04:05
The nested formats can be positional arguments. Position depends on the order of the opening curly braces:
This operation is not available with old-style formatting.
'{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)
+2.72
And of course keyword arguments can be added to the mix as before:
This operation is not available with old-style formatting.
'{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')
+2.72
网址是https://pyformat.info/#number_padding
Copyright © 2004-2024 Ynicp.com 版权所有 法律顾问:建纬(昆明)律师事务所 昆明市网翼通科技有限公司 滇ICP备08002592号-4