前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python format 使用 技巧

python format 使用 技巧

作者头像
bear_fish
发布2018-09-19 12:15:29
1.4K0
发布2018-09-19 12:15:29
举报
文章被收录于专栏:用户2442861的专栏

https://pyformat.info/

Basic formatting

Simple positional formatting is probably the most common use-case. Use it if the order of your arguments is not likely to change and you only have very few elements you want to concatenate.

Since the elements are not represented by something as descriptive as a name this simple style should only be used to format a relatively small number of elements.

Old

代码语言:javascript
复制
'%s %s' % ('one', 'two')

New

代码语言:javascript
复制
'{} {}'.format('one', 'two')

Output

代码语言:javascript
复制
one two

Old

代码语言:javascript
复制
'%d %d' % (1, 2)

New

代码语言:javascript
复制
'{} {}'.format(1, 2)

Output

代码语言:javascript
复制
1 2

With new style formatting it is possible (and in Python 2.6 even mandatory) to give placeholders an explicit positional index.

This allows for re-arranging the order of display without changing the arguments.

This operation is not available with old-style formatting.

New

代码语言:javascript
复制
'{1} {0}'.format('one', 'two')

Output

代码语言:javascript
复制
two one

Value conversion

The new-style simple formatter calls by default the __format__() method of an object for its representation. If you just want to render the output of str(...) or repr(...) you can use the !s or !r conversion flags.

In %-style you usually use %s for the string representation but there is %r for a repr(...) conversion.

Setup

代码语言:javascript
复制
class Data(object):

    def __str__(self):
        return 'str'

    def __repr__(self):
        return 'repr'

Old

代码语言:javascript
复制
'%s %r' % (Data(), Data())

New

代码语言:javascript
复制
'{0!s} {0!r}'.format(Data())

Output

代码语言:javascript
复制
str repr

In Python 3 there exists an additional conversion flag that uses the output of repr(...) but uses ascii(...)instead.

Setup

代码语言:javascript
复制
class Data(object):

    def __repr__(self):
        return 'räpr'

Old

代码语言:javascript
复制
'%r %a' % (Data(), Data())

New

代码语言:javascript
复制
'{0!r} {0!a}'.format(Data())

Output

代码语言:javascript
复制
räpr r\xe4pr

Padding and aligning strings

By default values are formatted to take up only as many characters as needed to represent the content. It is however also possible to define that a value should be padded to a specific length.

Unfortunately the default alignment differs between old and new style formatting. The old style defaults to right aligned while for new style it's left.

Align right:

Old

代码语言:javascript
复制
'%10s' % ('test',)

New

代码语言:javascript
复制
'{:>10}'.format('test')

Output

代码语言:javascript
复制
      test

Align left:

Old

代码语言:javascript
复制
'%-10s' % ('test',)

New

代码语言:javascript
复制
'{:10}'.format('test')

Output

代码语言:javascript
复制
test      

Again, new style formatting surpasses the old variant by providing more control over how values are padded and aligned.

You are able to choose the padding character:

This operation is not available with old-style formatting.

New

代码语言:javascript
复制
'{:_<10}'.format('test')

Output

代码语言:javascript
复制
test______

And also center align values:

This operation is not available with old-style formatting.

New

代码语言:javascript
复制
'{:^10}'.format('test')

Output

代码语言:javascript
复制
   test   

When using center alignment where the length of the string leads to an uneven split of the padding characters the extra character will be placed on the right side:

This operation is not available with old-style formatting.

New

代码语言:javascript
复制
'{:^6}'.format('zip')

Output

代码语言:javascript
复制
 zip  

Truncating long strings

Inverse to padding it is also possible to truncate overly long values to a specific number of characters.

The number behind a . in the format specifies the precision of the output. For strings that means that the output is truncated to the specified length. In our example this would be 5 characters.

Old

代码语言:javascript
复制
'%.5s' % ('xylophone',)

New

代码语言:javascript
复制
'{:.5}'.format('xylophone')

Output

代码语言:javascript
复制
xylop

Combining truncating and padding

It is also possible to combine truncating and padding:

Old

代码语言:javascript
复制
'%-10.5s' % ('xylophone',)

New

代码语言:javascript
复制
'{:10.5}'.format('xylophone')

Output

代码语言:javascript
复制
xylop     

Numbers

Of course it is also possible to format numbers.

Integers:

Old

代码语言:javascript
复制
'%d' % (42,)

New

代码语言:javascript
复制
'{:d}'.format(42)

Output

代码语言:javascript
复制
42

Floats:

Old

代码语言:javascript
复制
'%f' % (3.141592653589793,)

New

代码语言:javascript
复制
'{:f}'.format(3.141592653589793)

Output

代码语言:javascript
复制
3.141593

Padding numbers

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

Old

代码语言:javascript
复制
'%4d' % (42,)

New

代码语言:javascript
复制
'{:4d}'.format(42)

Output

代码语言:javascript
复制
  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

代码语言:javascript
复制
'%06.2f' % (3.141592653589793,)

New

代码语言:javascript
复制
'{:06.2f}'.format(3.141592653589793)

Output

代码语言:javascript
复制
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

代码语言:javascript
复制
'%04d' % (42,)

New

代码语言:javascript
复制
'{:04d}'.format(42)

Output

代码语言:javascript
复制
0042

Signed numbers

By default only negative numbers are prefixed with a sign. This can be changed of course.

Old

代码语言:javascript
复制
'%+d' % (42,)

New

代码语言:javascript
复制
'{:+d}'.format(42)

Output

代码语言:javascript
复制
+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

代码语言:javascript
复制
'% d' % ((- 23),)

New

代码语言:javascript
复制
'{: d}'.format((- 23))

Output

代码语言:javascript
复制
-23

Old

代码语言:javascript
复制
'% d' % (42,)

New

代码语言:javascript
复制
'{: d}'.format(42)

Output

代码语言:javascript
复制
 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

代码语言:javascript
复制
'{:=5d}'.format((- 23))

Output

代码语言:javascript
复制
-  23

New

代码语言:javascript
复制
'{:=+5d}'.format(23)

Output

代码语言:javascript
复制
+  23

Named placeholders

Both formatting styles support named placeholders.

Setup

代码语言:javascript
复制
data = {'first': 'Hodor', 'last': 'Hodor!'}

Old

代码语言:javascript
复制
'%(first)s %(last)s' % data

New

代码语言:javascript
复制
'{first} {last}'.format(**data)

Output

代码语言:javascript
复制
Hodor Hodor!

.format() also accepts keyword arguments.

This operation is not available with old-style formatting.

New

代码语言:javascript
复制
'{first} {last}'.format(first='Hodor', last='Hodor!')

Output

代码语言:javascript
复制
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

代码语言:javascript
复制
person = {'first': 'Jean-Luc', 'last': 'Picard'}

New

代码语言:javascript
复制
'{p[first]} {p[last]}'.format(p=person)

Output

代码语言:javascript
复制
Jean-Luc Picard

Setup

代码语言:javascript
复制
data = [4, 8, 15, 16, 23, 42]

New

代码语言:javascript
复制
'{d[4]} {d[5]}'.format(d=data)

Output

代码语言:javascript
复制
23 42

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

This operation is not available with old-style formatting.

Setup

代码语言:javascript
复制
class Plant(object):
    type = 'tree'

New

代码语言:javascript
复制
'{p.type}'.format(p=Plant())

Output

代码语言:javascript
复制
tree

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

This operation is not available with old-style formatting.

Setup

代码语言:javascript
复制
class Plant(object):
    type = 'tree'
    kinds = [{'name': 'oak'}, {'name': 'maple'}]

New

代码语言:javascript
复制
'{p.type}: {p.kinds[0][name]}'.format(p=Plant())

Output

代码语言:javascript
复制
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

代码语言:javascript
复制
from datetime import datetime

New

代码语言:javascript
复制
'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))

Output

代码语言:javascript
复制
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

代码语言:javascript
复制
'{:{align}{width}}'.format('test', align='^', width='10')

Output

代码语言:javascript
复制
   test   

Parametrized precision:

Old

代码语言:javascript
复制
'%.*s = %.*f' % (3, 'Gibberish', 3, 2.7182)

New

代码语言:javascript
复制
'{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3)

Output

代码语言:javascript
复制
Gib = 2.718

Width and precision:

Old

代码语言:javascript
复制
'%*.*f' % (5, 2, 2.7182)

New

代码语言:javascript
复制
'{:{width}.{prec}f}'.format(2.7182, width=5, prec=2)

Output

代码语言:javascript
复制
 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

代码语言:javascript
复制
'{:{prec}} = {:{prec}}'.format('Gibberish', 2.7182, prec='.3')

Output

代码语言:javascript
复制
Gib = 2.72

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

This operation is not available with old-style formatting.

Setup

代码语言:javascript
复制
from datetime import datetime
dt = datetime(2001, 2, 3, 4, 5)

New

代码语言:javascript
复制
'{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')

Output

代码语言:javascript
复制
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

代码语言:javascript
复制
'{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)

Output

代码语言:javascript
复制
     +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

代码语言:javascript
复制
'{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')

Output

代码语言:javascript
复制
     +2.72

Custom objects

The datetime example works through the use of the __format__() magic method. You can define custom format handling in your own objects by overriding this method. This gives you complete control over the format syntax used.

This operation is not available with old-style formatting.

Setup

代码语言:javascript
复制
class HAL9000(object):

    def __format__(self, format):
        if (format == 'open-the-pod-bay-doors'):
            return "I'm afraid I can't do that."
        return 'HAL 9000'

New

代码语言:javascript
复制
'{:open-the-pod-bay-doors}'.format(HAL9000())

Output

代码语言:javascript
复制
I'm afraid I can't do that.
代码语言:javascript
复制
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017年01月13日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • https://pyformat.info/
  • Basic formatting
    • Old
      • New
        • Output
          • Old
            • New
              • Output
                • New
                  • Output
                  • Value conversion
                    • Setup
                      • Old
                        • New
                          • Output
                            • Setup
                              • Old
                                • New
                                  • Output
                                  • Padding and aligning strings
                                    • Old
                                      • New
                                        • Output
                                          • Old
                                            • New
                                              • Output
                                                • New
                                                  • Output
                                                    • New
                                                      • Output
                                                        • New
                                                          • Output
                                                          • Truncating long strings
                                                            • Old
                                                              • New
                                                                • Output
                                                                • Combining truncating and padding
                                                                  • Old
                                                                    • New
                                                                      • Output
                                                                      • Numbers
                                                                        • Old
                                                                          • New
                                                                            • Output
                                                                              • Old
                                                                                • New
                                                                                  • Output
                                                                                  • Padding numbers
                                                                                    • Old
                                                                                      • New
                                                                                        • Output
                                                                                          • Old
                                                                                            • New
                                                                                              • Output
                                                                                                • Old
                                                                                                  • New
                                                                                                    • Output
                                                                                                    • Signed numbers
                                                                                                      • Old
                                                                                                        • New
                                                                                                          • Output
                                                                                                            • Old
                                                                                                              • New
                                                                                                                • Output
                                                                                                                  • Old
                                                                                                                    • New
                                                                                                                      • Output
                                                                                                                        • New
                                                                                                                          • Output
                                                                                                                            • New
                                                                                                                              • Output
                                                                                                                              • Named placeholders
                                                                                                                                • Setup
                                                                                                                                  • Old
                                                                                                                                    • New
                                                                                                                                      • Output
                                                                                                                                        • New
                                                                                                                                          • Output
                                                                                                                                          • Getitem and Getattr
                                                                                                                                            • Setup
                                                                                                                                              • New
                                                                                                                                                • Output
                                                                                                                                                  • Setup
                                                                                                                                                    • New
                                                                                                                                                      • Output
                                                                                                                                                        • Setup
                                                                                                                                                          • New
                                                                                                                                                            • Output
                                                                                                                                                              • Setup
                                                                                                                                                                • New
                                                                                                                                                                  • Output
                                                                                                                                                                  • Datetime
                                                                                                                                                                    • Setup
                                                                                                                                                                      • New
                                                                                                                                                                        • Output
                                                                                                                                                                        • Parametrized formats
                                                                                                                                                                          • New
                                                                                                                                                                            • Output
                                                                                                                                                                              • Old
                                                                                                                                                                                • New
                                                                                                                                                                                  • Output
                                                                                                                                                                                    • Old
                                                                                                                                                                                      • New
                                                                                                                                                                                        • Output
                                                                                                                                                                                          • New
                                                                                                                                                                                            • Output
                                                                                                                                                                                              • Setup
                                                                                                                                                                                                • New
                                                                                                                                                                                                  • Output
                                                                                                                                                                                                    • New
                                                                                                                                                                                                      • Output
                                                                                                                                                                                                        • New
                                                                                                                                                                                                          • Output
                                                                                                                                                                                                          • Custom objects
                                                                                                                                                                                                            • Setup
                                                                                                                                                                                                              • New
                                                                                                                                                                                                                • Output
                                                                                                                                                                                                                领券
                                                                                                                                                                                                                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档