如果需要{}是自己实际需要的字符,需要用{{}}作为转义

以下转自: 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

'%s %s' % ('one', 'two')

New

'{} {}'.format('one', 'two')

Output

one two

Old

'%d %d' % (1, 2)

New

'{} {}'.format(1, 2)

Output

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

'{1} {0}'.format('one', 'two')

Output

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

class Data(object):def __str__(self):return 'str'def __repr__(self):return 'repr'

Old

'%s %r' % (Data(), Data())

New

'{0!s} {0!r}'.format(Data())

Output

str repr

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

Setup

class Data(object):def __repr__(self):return 'räpr'

Old

'%r %a' % (Data(), Data())

New

'{0!r} {0!a}'.format(Data())

Output

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

'%10s' % ('test',)

New

'{:>10}'.format('test')

Output

      test

Align left:

Old

'%-10s' % ('test',)

New

'{:10}'.format('test')

Output

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

'{:_<10}'.format('test')

Output

test______

And also center align values:

This operation is not available with old-style formatting.

New

'{:^10}'.format('test')

Output

   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

'{:^6}'.format('zip')

Output

 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

'%.5s' % ('xylophone',)

New

'{:.5}'.format('xylophone')

Output

xylop

Combining truncating and padding

It is also possible to combine truncating and padding:

Old

'%-10.5s' % ('xylophone',)

New

'{:10.5}'.format('xylophone')

Output

xylop     

Numbers

Of course it is also possible to format numbers.

Integers:

Old

'%d' % (42,)

New

'{:d}'.format(42)

Output

42

Floats:

Old

'%f' % (3.141592653589793,)

New

'{:f}'.format(3.141592653589793)

Output

3.141593

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

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

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

'{:open-the-pod-bay-doors}'.format(HAL9000())

Output

I'm afraid I can't do that.

Python format 使用实例相关推荐

  1. python format函数实例_python中强大的format函数实例详解

    python中format函数用于字符串的格式化 自python2.6开始,新增了一种格式化字符串的函数str.format(),此函数可以快速处理各种字符串. 语法 它通过{}和:来代替%. 请看下 ...

  2. python format函数实例_Python字符串格式化,format格式化函数详细使用

    Python接触比较多的是字符串,那么操作字符串也就多.Python 支持格式化字符串的输出 . 尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符的字符串中. 代码 ...

  3. python format函数实例_【Python】-String的Format格式规约函数及实例

    #字符串格式规约 #format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] #参数详解 #fill ::= ,填充字 ...

  4. python基础语法手册format-python的格式化输出(format,%)实例详解

    皇城PK Python中格式化字符串目前有两种阵营:%和format,我们应该选择哪种呢? 自从Python2.6引入了format这个格式化字符串的方法之后,我认为%还是format这根本就不算个问 ...

  5. python Format()函数的用法___实例详解(一)(全,例多)___各种格式化替换,format对齐打印

    python Format()函数的用法___实例详解(一)(全,例多) (格式化替换,关键字替换,列表字典替换,类格式化, 魔法函数格式化,对齐及填充格式化,format对齐打印) 本篇目录内容:

  6. 从入门到入土:Python爬虫学习|实例练手|爬取猫眼榜单|Xpath定位标签爬取|代码

    此博客仅用于记录个人学习进度,学识浅薄,若有错误观点欢迎评论区指出.欢迎各位前来交流.(部分材料来源网络,若有侵权,立即删除) 本人博客所有文章纯属学习之用,不涉及商业利益.不合适引用,自当删除! 若 ...

  7. 从入门到入土:Python爬虫学习|实例练手|爬取百度翻译|Selenium出击|绕过反爬机制|

    此博客仅用于记录个人学习进度,学识浅薄,若有错误观点欢迎评论区指出.欢迎各位前来交流.(部分材料来源网络,若有侵权,立即删除) 本人博客所有文章纯属学习之用,不涉及商业利益.不合适引用,自当删除! 若 ...

  8. 从入门到入土:Python爬虫学习|实例练手|爬取新浪新闻搜索指定内容|Xpath定位标签爬取|代码注释详解

    此博客仅用于记录个人学习进度,学识浅薄,若有错误观点欢迎评论区指出.欢迎各位前来交流.(部分材料来源网络,若有侵权,立即删除) 本人博客所有文章纯属学习之用,不涉及商业利益.不合适引用,自当删除! 若 ...

  9. 从入门到入土:Python爬虫学习|实例练手|爬取百度产品列表|Xpath定位标签爬取|代码注释详解

    此博客仅用于记录个人学习进度,学识浅薄,若有错误观点欢迎评论区指出.欢迎各位前来交流.(部分材料来源网络,若有侵权,立即删除) 本人博客所有文章纯属学习之用,不涉及商业利益.不合适引用,自当删除! 若 ...

  10. python简单程序实例-python简单实例训练(21~30)

    注意:我用的python2.7,大家如果用Python3.0以上的版本,请记得在print()函数哦!如果因为版本问题评论的,不做回复哦!! 21.题目:将一个正整数分解质因数.例如:输入90,打印出 ...

最新文章

  1. Linux C定时器使用指南
  2. OpenShift 与 OpenStack:让云变得更简单
  3. 收集18个高大上的浏览器小技巧
  4. K8S Learning(10)——Pod配置
  5. XSS-Game Level 4
  6. python :super 的作用
  7. 新华三模拟器STP和RSTP及其MSTP的作用与配置
  8. 内核block层IO调度器—bfq算法深入探索3
  9. windows11 微信双开的方法
  10. Moya 设置超时时间和请求头
  11. no matching function for call to ‘cv2eigen‘
  12. 组建Ad Hoc模式无线局域网
  13. java程序员必备英语词汇_java程序员常用英文单词整理
  14. 电磁元件(电阻,电容与电感)
  15. android相册和拍照并裁剪图片大小,Android 拍照并对照片进行裁剪和压缩实例详解...
  16. unity3dk帧_Unity K帧动画
  17. Hi3516A/Hi3516D SDK 安装以及升级使用说明
  18. C语言中,#include的用法:#include 和 #include区别
  19. 雨伞16骨好还是24骨好_伞骨什么材质好 晴雨伞骨数越多越好吗
  20. 谏言工信部:网站备案系统miibeian.gov.cn实在难用!

热门文章

  1. 论文浏览(45) MiCT: Mixed 3D/2D Convolutional Tube for Human Action Recognition
  2. html剧场座位设计图,报告厅舞台到第一排的距离多少合适 剧院主舞台离座位最佳距离尺寸设计图...
  3. Python随机函数
  4. Kong 开源的服务网格Kuma爬过了K8S这座大山
  5. 新能源电动汽车(EV)直流充电协议
  6. C# 操作Word文本框——插入图片、表格、文字、超链接等
  7. JavaSE基础20笔记IO流
  8. 编译 nginx + http-flv 模块
  9. 基于Bilibili开源flv.js拉流
  10. vscode配置运行php项目完整版