VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > 数据分析 >
  • Python .format()的详细使用(英文版)

英文原文在这儿:https://pyformat.info/#number_padding

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


相关教程