Python format 格式化函数

一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。
1)不设置指定位置,按默认顺序
>>> '{} {}'.format('hello', 'world')
'hello world'

2)设置指定位置
>>> '{0} {1}'.format('hello', 'world')
'hello world'

3)设置指定位置2
>>> '{1} {0} {1}'.format('hello', 'world')
'world hello world'

4)直接设置参数
>>> print('网站名:{name}, 地址{url}'.format(name='OA', url='www.chinamobile.com'))
网站名:OA, 地址www.chinamobile.com

5)通过字典设置参数
>>> site = {'name': 'OA', 'url': 'www.chinamobile.com'}
>>> print('网站名:{name}, 地址:{url}'.format(**site))
网站名:OA, 地址:www.chinamobile.com

6)通过列表索引设置参数
>>> my_list = ['OA', 'www.chinamobile.com']
>>> print('网站名:{0[0]}, 地址:{0[1]}'.format(my_list))
网站名:OA, 地址:www.chinamobile.com

7)向 str.format() 传入对象
>>> class AssignValue(object):
def __init__(self, value):
self.value = value
>>> my_value = AssignValue(6)
>>> print('value: {0.value}'.format(my_value))
value: 6

8)数字格式化
>>> print('{:.2f}'.format(3.1415926))
3.14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值