python的字符串格式化有两种,分别是占位符和format方式。主要记录下format的用法
一、占位符(%)
下面列举下常用的占位符格式
%s | 字符串 |
%d | 整数 |
%f | 浮点数组 |
示例1
name ="lvyq"
print("name is : %s"%name)
运行结果
示例2
name = "lvyq"
age = 12
msg = "name is : %s ,age is :%d" %(name,age)
print(msg)
执行结果
二、format()
再format函数中,使用“{}”符号来当作格式化操作符
以下以name=“lvyq”,age = 12 为例
1.位置映射
"name is:{},age is :{}".format(name,age)
name = "lvyq"
age = 12
msg1 = "name is:{},age is :{}".format(name,age)
msg2 = "name is:{0},age is :{1}".format(name,age)
msg3 = "name is:{1},age is :{1}".format(name,age)
print(msg1)
print(msg2)
print(msg3)
运行结果
由结果,可以看出,是以索引的方式进行赋值的,默认不填写索引值的情况下,按照索引从0自增的方式赋值
2.关键字映射
"name is:{name},age is :{age}".format(name=name,age=age)
name = "lvyq"
age = 12
msg1 = "name is:{name},age is :{age}".format(name=name,age=age)
msg2 = "name is:{age},age is :{name}".format(name=name,age=age)
print(msg1)
print(msg2)
运行结果
msg2的输出是为了验证,故意写的
3.元素下标
"name is:{0[0]},age is :{0[1]}".format(user)
user=["lvyq","12"]
msg1="name is:{0[0]},age is :{0[1]}".format(user)
msg2="name is:{0[1]},age is :{0[0]}".format(user)
print(msg1)
#验证对比输出
print(msg2)
运行结果
扩展
user = [["lvyq","12"],["xiaoming","13"]]
msg1 = "name is:{0[0]},age is :{0[1]}".format(user[0])
msg2 = "name is:{0[0]},age is :{0[1]}".format(user[1])
print(msg1)
print(msg2)
运行结果
4.填充对齐
1 ^、<、>分别是居中、左对齐、右对齐,后面带宽度
2 :号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
"name is:{:*^6}".format(name)
name = "lvyq"
msg1 = "居中 name is:{:*^6}".format(name)
msg2 = "左对齐 name is:{:<6}".format(name)
msg3 = "右对齐 name is:{:>6}".format(name)
msg4 = "宽度小于name的长度 name is:{:*<3}".format(name)
print(msg1)
print(msg2)
print(msg3)
print(msg4)
运行结果
由结果可以看出,当宽度小于变量值时,对齐宽度为0,变量值的显示不受影响
5.浮点数精度
"{:.2f}".format(num)
num = 1.23456
msg1 ="{:.2f}".format(num)
msg2 ="{:.3f}".format(num)
print(msg1)
print(msg2)
运行结果
6.千分位分割
"{:,}".format(num)
num = 123456
msg="{:,}".format(num)
print(msg)
运行结果