Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序。
实例
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
也可以设置参数:
实例
print("{year}年{month}月".format(year="2021", month="11"))
# 通过字典设置参数
date = {"year": "2021", "month": "11"}
print("{year}年{month}月".format(**date))
# 通过列表索引设置参数
date = ['2021', '11']
print("{0[0]}年{0[1]}月".format(date))
输出结果为:
2021年11月
2021年11月
2021年11月
数字格式化
>>> print("{:.2f}".format(3.1415926))
3.14
>>> print("{:02d}".format(1))
01
>>> print("{:b}".format(100))
1100100
>>> print("{:d}".format(100))
100
>>> print("{:o}".format(100))
144
>>> print("{:x}".format(100))
64
b、d、o、x 分别是二进制、十进制、八进制、十六进制
编程练习
输出事件日志字符串
输入:name="点击买入按钮",time="2021-11-01 11:11:30"
输出:Event:点击买入按钮,Time:2021-11-01 11:11:30
Python在线编程练习:https://lab.youkuaiyun.com/suite_show/164