一种格式化字符串的函数 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
基本语法是通过 {} 和 : 来代替以前的 % 。
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