Python格式化输出之format用法详解
本文详解Python中format函数的核心用法,涵盖无参、关键字及魔法参数的字符串填充技巧,深入解析数字格式化的各种修饰符,并阐明叹号(!s, !r, !a)在类型转换中的作用,帮助开发者掌握高效且灵活的格式化输出方案。
format用法
相较于传统的百分号(%)格式化方式,Python的format()函数提供了更强大的功能。它将字符串视为模板,通过传入的参数进行格式化操作,并使用大括号({})作为占位符来替代百分号。
该函数的调用方式主要有两种:一种是实例方法调用b.format(a),另一种是内置函数调用format(a, b)。
一、填充
1.无参(1)
print('{} {}'.format('hello','world'))
hello world
2.无参(2)
print('{0} {1}'.format('hello','world'))
hello world
3.无参(3)
print('{1} {0} {1}'.format('hello','world'))
world hello world
4.key value
print('ID:{id},Name:{name}'.format(id='001',name='hello'))
ID:001,Name:hello
5.列表
list=['001','hello']
print('ID:{List[0]},Name:{List[1]}'.format(List = list))
print('ID:{0[0]},Name:{0[1]}'.format(list))
ID:001,Name:hello ID:001,Name:hello
6.字典
dict={'id':'001,'name':'hello'}
print('ID:{Dict[0]},Name:{Dict[1]}'.format(Dict = dict))
print('ID:{id},Name:{name}'.format(**dict))
ID:001,Name:hello ID:001,Name:hello
7.类
class value():
id = '001'
name = 'hello'
print('ID:{Value.id},Name{Value.name}'.format(Value = value))
ID:001,Name:hello
8.魔法参数
*args用于接收任意数量的无名参数,其结果为一个元组或列表;**kwargs用于接收关键字参数,其结果为一个字典。
args = [',','.']
kwargs = {'id': '001','name':'hello'}
print('ID:{id}{}Name:{name}{}'.format(*args, **kwargs))
ID:001,Name:hello.
二、数字格式化
| 数字 | 格式 | 输出 | 描述 |
|---|---|---|---|
| 3.1415926 | {:.2f} | 3.14 | 保留小数点后两位 |
| 3.1415926 | {:+.2f} | +3.14 | 带符号保留小数点后两位 |
| -1 | {:+.2f} | -1.00 | 带符号保留小数点后两位 |
| 2.71828 | {:.0f} | 3 | 不带小数 |
| 5 | {:0>2d} | 05 | 数字补零 (填充左边, 宽度为2) |
| 5 | {:x<4d} | 5xxx ) | 数字补x (填充右边, 宽度为4 |
| 10 | {:x<4d} | 10xx ) | 数字补x (填充右边, 宽度为4 |
| 1000000 | {:,} | 1,000,000 | 以逗号分隔的数字格式 |
| 0.25 | {:.2%} | 25.00% | 百分比格式 |
| 1000000000 | {:.2e} | 1.00e+09 | 指数记法 |
| 13 | {:>10d} | 13 | 右对齐 (默认, 宽度为10) |
| 13 | {:<10d} | 13 | 左对齐 (宽度为10) |
| 13 | {:^10d} | 13 | 中间对齐 (宽度为10) |
| 11 | ‘{:b}’.format(11) | 1011 | 二进制 |
| 11 | ‘{:d}’.format(11) | 11 | 十进制 |
| 11 | ‘{:o}’.format(11) | 13 | 八进制 //这里打成中文的冒号了,因为用英文的会打出一个O的表情~~~ |
| 11 | ‘{:x}’.format(11) | b | 十六进制 |
| 11 | ‘{:#x}’.format(11) | 0xb | 0x式十六进制+小写 |
| 11 | ‘{:#X}’.format(11) | 0xB | 0x式十六进制+大写 |
三、叹号用法
print(‘{!s}好'.format(‘你'))
print(‘{!r}好'.format(‘你'))
print(‘{!a}好'.format(‘你'))
你好 ’你’好 ’\u4f60’好
叹号(!)后跟随s、r或a,分别对应调用str()、repr()和ascii()函数。其作用是在执行填充操作之前,先对参数应用相应的类型转换函数。
三者的主要区别在于:
str()面向最终用户,旨在提供易读的输出结果;
repr()通常带有引号,用于展示对象的官方字符串表示;
ascii()面向Python解析器,其返回值旨在表示Python内部的含义,且仅返回ASCII编码范围内的字符。
总结
至此,关于Python格式化输出中format用法的介绍已完成。如需了解更多相关Python格式化输出内容,建议查阅本站过往文章或继续浏览后续教程,感谢支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













