Python format 格式化函数
实例
format 函数可以接受不限个参数,位置可以不按顺序。
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
也可以设置参数:
print("姓名:{name}, 职业:{job}".format(name="中森先生", job="学生"))
# 通过字典设置参数
my_dict = {"name":"中森先生", "job": "学生"}
print("姓名:{name}, 职业:{job}".format(**dict))
# 通过列表索引设置参数
my_list = ['中森先生', '学生']
print("姓名:{0[0]}, 职业:{0[1]}".format(my_list)) # "0" 是必须的
也可以向 format() 传入对象:
class Test(object):
def __init__(self, job):
self.job = job
my_job = Test('学生')
print('中森先生的职业为: {0.job}'.format(my_job)) # "0" 是可选的
本文介绍了Python的format函数,包括如何设置参数位置、传递字典和列表参数,以及如何格式化输出对象属性。示例展示了format函数在字符串格式化中的灵活性。

被折叠的 条评论
为什么被折叠?



