欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python .format()的详细使用(英文版)

程序员文章站 2022-03-26 21:48:46
英文原文在这儿:https://pyformat.info/#number_padding Padding numbers Similar to strings numbers can also be constrained to a specific width. Old '%4d' % (42, ......

英文原文在这儿:

padding numbers

similar to strings numbers can also be constrained to a specific width.

old

'%4d' % (42,)

new

'{:4d}'.format(42)

output

  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.

old

'%06.2f' % (3.141592653589793,)

new

'{:06.2f}'.format(3.141592653589793)

output

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).

old

'%04d' % (42,)

new

'{:04d}'.format(42)

output

0042

signed numbers

by default only negative numbers are prefixed with a sign. this can be changed of course.

old

'%+d' % (42,)

new

'{:+d}'.format(42)

output

+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.

old

'% d' % ((- 23),)

new

'{: d}'.format((- 23))

output

-23

old

'% d' % (42,)

new

'{: d}'.format(42)

output

 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.

new

'{:=5d}'.format((- 23))

output

-  23

new

'{:=+5d}'.format(23)

output

+  23

named placeholders

both formatting styles support named placeholders.

setup

data = {'first': 'hodor', 'last': 'hodor!'}

old

'%(first)s %(last)s' % data

new

'{first} {last}'.format(**data)

output

hodor hodor!

.format() also accepts keyword arguments.

this operation is not available with old-style formatting.

new

'{first} {last}'.format(first='hodor', last='hodor!')

output

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.

setup

person = {'first': 'jean-luc', 'last': 'picard'}

new

'{p[first]} {p[last]}'.format(p=person)

output

jean-luc picard

setup

data = [4, 8, 15, 16, 23, 42]

new

'{d[4]} {d[5]}'.format(d=data)

output

23 42

as well as accessing attributes on objects via getattr():

this operation is not available with old-style formatting.

setup

class plant(object):
    type = 'tree'

new

'{p.type}'.format(p=plant())

output

tree

both type of access can be freely mixed and arbitrarily nested:

this operation is not available with old-style formatting.

setup

class plant(object):
    type = 'tree'
    kinds = [{'name': 'oak'}, {'name': 'maple'}]

new

'{p.type}: {p.kinds[0][name]}'.format(p=plant())

output

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.

setup

from datetime import datetime

new

'{:%y-%m-%d %h:%m}'.format(datetime(2001, 2, 3, 4, 5))

output

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.

new

'{:{align}{width}}'.format('test', align='^', width='10')

output

   test   

parametrized precision:

old

'%.*s = %.*f' % (3, 'gibberish', 3, 2.7182)

new

'{:.{prec}} = {:.{prec}f}'.format('gibberish', 2.7182, prec=3)

output

gib = 2.718

width and precision:

old

'%*.*f' % (5, 2, 2.7182)

new

'{:{width}.{prec}f}'.format(2.7182, width=5, prec=2)

output

 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.

new

'{:{prec}} = {:{prec}}'.format('gibberish', 2.7182, prec='.3')

output

gib = 2.72

the components of a date-time can be set separately:

this operation is not available with old-style formatting.

setup

from datetime import datetime
dt = datetime(2001, 2, 3, 4, 5)

new

'{:{dfmt} {tfmt}}'.format(dt, dfmt='%y-%m-%d', tfmt='%h:%m')

output

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.

new

'{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)

output

     +2.72

and of course keyword arguments can be added to the mix as before:

this operation is not available with old-style formatting.

new

'{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')

output

     +2.72

网址是https://pyformat.info/#number_padding