python:格式化字符串,format

本文介绍Python中使用format方法格式化字符串的各种技巧,包括位置参数、关键字操作、填充与格式化、精度与进制以及索引使用等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python中format格式化字符串比 % 提供更加强大的输出特性

1、位置参数

format的元素输出流位置参数不受顺序约束,元素放置方式为{},只要format里有相对应的参数值即可,参数索引从0开始,传入位置参数列表时可用*进行读取

>>> myinfo = ['oldpan',22]
>>> print('my name is {}, age {}'.format('oldpan', 22))
my name is oldpan, age 22
>>> print('my name is {1}, age {0}'.format(22,'oldpan'))
my name is oldpan, age 22
>>> print('my name is {1}, age {0},and they often call me {1},'.format(22,'oldpan'))
my name is oldpan, age 22,and they often call me oldpan,
>>> print('my name is {}, age {}'.format(*myinfo))
my name is oldpan, age 22

2、使用关键字操作

只要关键字对的上,format也可以像字典一样进行操作

>>> myinfo = {'name':'oldpan','age':22}
>>> print('my name is {name}, age {age}'.format(name='oldpan', age=22))
my name is oldpan, age 22
>>> print('my name is {name}, age {age}'.format(**myinfo))
my name is oldpan, age 22

3、填充与格式化

使用格式为: [填充字符][对齐方式 <^>][宽度]

>>> '{0:*>10}'.format(10)    # 右对齐
'********10'
>>> '{0:*<10}'.format(10)    # 左对齐
'10********'
>>> '{0:*^10}'.format(10)    # 居中对齐
'****10****'

4、精度与进制

>>> '{0:.2f}'.format(1/3)
'0.33'
>>> '{0:b}'.format(10)     # 二进制
'1010'
>>> '{0:o}'.format(10)     # 八进制
'12'
>>> '{0:x}'.format(10)     # 16进制
'a'
>>> '{:,}'.format(12369132698)  # 千分位格式化
'12,369,132,698'

5、使用索引

>>> li
['hoho', 18]
>>> 'name is {0[0]} age is {0[1]}'.format(li)
'name is hoho age is 18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老潘的博客

请老潘吃块饼干!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值