python中format函数

约定不等于承诺〃 2022-02-01 11:11 355阅读 0赞

python中format函数用于字符串的格式化


通过关键字

1.

  1. print('{name}在{option}'.format(name="谢某人"option="写代码"))

结果:谢某人在写代码


通过位置
1.

  1. print('name={} path={}'.format('zhangsan', '/')

结果:name=zhangsan path=/

2.

  1. print('{1}在{0}'.format('写代码','谢某人'))

3.

  1. print('{0}在{1}'.format('谢某人','写代码'))

结果:谢某人在写代码


填充和对齐^<>分别表示居中、左对齐、右对齐,后面带宽度

  1. print('{:^30}'.format("zhangsan")) # 居中
  2. print('{:>30}'.format("zhangsan")) # 右对齐
  3. print('{:<30}'.format("zhangsan")) # 左对齐
  4. 30:字段长度(最左到最右之间的长度)

结果显示

精度控制 :.nf

1.

  1. print('{:.2f}'.format(3.14159))
  2. 结果:3.14
  3. 保留两位小数,两位后四舍五入

2.

  1. print('{:.5f}'.format(3.14))
  2. 结果:3.14000
  3. 保留5位小数,不足补0.
  4. 进制转化,b o d x 分别表示二、八、十、十六进制
  5. print('{:b}'.format(20))
  6. print('{:o}'.format(20))
  7. print('{:d}'.format(20))
  8. print('{:x}'.format(20))

结果:

10100
24
20
14


千位分隔符::,

  1. print('{:,}'.format(100000000))
  2. print('{:,}'.format(123456.123456))

结果:

100,000,000
123,456.123456

发表评论

表情:
评论列表 (有 0 条评论,355人围观)

还没有评论,来说两句吧...

相关阅读