函数 str.format()
,它增强了字符串格式化的功能。
基本语法是通过 {} 和 : 来代替以前的 % 。
format 函数可以接受不限个参数,位置可以不按顺序
实例1(不设置参数):
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
实例2(设置参数):
print("{f} {l}".format(f="hello", l="world"))
# 通过字典设置参数
site = {"f": "hello", "l": "world"}
print("{f} {l}".format(**site))
# 通过列表索引设置参数
my_list = ['hello', 'world']
print("{0[0]} {0[1]}".format(my_list)) # "0" 是必须的
输出:
hello world
hello world
hello world
实例3(数字格式化):
>>> print("{:.2f}".format(3.1415926))
3.14
^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格
b、d、o、x 分别是二进制、十进制、八进制、十六进制。