%、.format()格式化

%格式化形式:

%[(name)][flags][width].[precition]typecode

name:(可选)用于选择指定的key
flags:(可选)+左对齐、-右对齐
width:(可选)宽度
preciton:(可选)精度,默认位保留6位
typecode:必选
s:字符串类型,但可以放入任何类型
f:浮点数,默认保留6位
b:将数字转换为2进制放入指定位置
d:将数字转为整型放入指定位置
x:将数字转为十六进制放入指定位置

几个例子

 message = "I am %.s , my hobby is swim" %'alex'
print(message)

传入浮点数并设置精度

message = "percent %.f" % 99.12345678
print(message)

传入字典

message = "I am %(name)s, age%(age)d"%{"name":"alex", "age":18}
print(message)

出现百分号

message = "percent%.2f %%"%99.1234
print(message)

.format()格式化形式

字符串.format(字符串、数字等)

几个例子
按照引索替换

s = "I am {0},age{1[2]}".format("Alex", [16, 17, 18])
print(s)

按照key替换

s = "I am {name},age{age}".format(name = "Alex", age = 18)
print(s)

当.format()格式化占位符内未输入引索或key则按照顺序替换。

s = "I am {}, age{}".format("alex", 18)
print(s)

.format()格式化括号内的值必须比占位符要多,少于占位符会报错,多余占位符无影响

s = "I am {}, age{}".format("alex", 18, 19, 20)
print(s)

.format()传入字典

s = "I am {name}, age{age}".format(**{"name" : "alex", "age" : 18})
print(s)

.format()传入列表

s = "I am {1}, age {2}".format(*[0, "alex", 18])
print(s)

占位符内可带参数,表明需要转换为的类型

s = "I am {0:s}, age{1:x}".format("Alex", 18)
print(s)

猜你喜欢

转载自blog.csdn.net/weixin_43690603/article/details/84235066