Python format 字符串格式化函数

Python format 字符串格式化函数,第1张

Python format 字符串格式化函数 Python format 字符串格式化函数 一、简介

从Python2.6开始,新增了str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 : 来代替以前的 % 占位符。

二、占位符%方式

字符串格式符号用法如下

举个例子:

name = 'sugar'
age = 21
print("His name is %s, and he is %d year old." %(name, age))

结果

His name is sugar, and he is 21 year old.

其他格式化辅助 *** 作指令如下,其中用的比较多的就是使用0来补零,和控制小数位数的.

举个例子:

price = 23.1999
obj = 'milk'

print("The %s's price is %03f" %(obj, price))  # 前面补三个零
print("The %s's price is %3.0f" %(obj, price))  # 最小总占位长度为3,控制输出0个小数
print("The %s's price is %3.3f" %(obj, price))  # 最小总占位长度为3,控制输出3个小数
print("The %s's price is %5.4f" %(obj, price))  # 最小总占位长度为5,控制输出4个小数

结果:

The milk's price is 23.199900
The milk's price is  23
The milk's price is 23.200
The milk's price is 23.1999
三、format格式化方式

字符串format格式化的四种方式

1、使用默认位置方式

格式:string{}.format(x1, x2)
举个例子

price = 23.1999
obj = 'milk'
print("The {}'s price is {}".format(obj, price))

结果如下

The milk's price is 23.1999
2、使用指定位置方式

格式:string{0}.format(x1, x2)
举个例子

price = 23.1999
obj = 'milk'
print("The {0}'s price is {1}".format(obj, price))

结果如下

The milk's price is 23.1999
3、使用列表方式

其实这种方式就相当于前两种使用默认位置和使用指定位置的方式,只不过这里需要使用*对列表进行解包,举个例子

price = 23.1999
obj = 'milk'
info = [obj, price]
print("The {}'s price is {}".format(*info))  # 对info进行解包

结果如下

The milk's price is 23.1999
4、使用字典的键值对方式

格式:string(key).format(key=value)

举个例子,当然也可以用**对字典进行解包

price = 23.1999
obj = 'milk'
print("The {name}'s price is {pri}".format(name=obj, pri=price))

# 更进一步,对字典进行解包
dic = {'name':'milk', 'pri':23.1999}
print("The {name}'s price is {pri}".format(**dic))

结果如下

The milk's price is 23.1999
The milk's price is 23.1999
5、其他数字格式化的方式


需要注意的是,在:冒号后面指定需要填充的内容,可以使用上述4种格式化方式来对文本格式进行控制,举个例子

price = 23.1999
obj = 'bread'
print("The {}'s price is {:.2f}".format(obj, price))  # 使用默认位置方式,保留两位小数
print("The {0}'s price is {1:.2f}".format(obj, price))  # 使用指定位置方式,保留两位小数
print("The {name}'s price is {price:.2f}".format(name=obj, price=price))  # 使用字典方式,保留两位小数

li = [obj, price]
print("The {}'s price is {:.2f}".format(*li))  # 使用列表解包的方式,保留两位小数

info = {'name':obj, 'price':price}
print("The {name}'s price is {price:.2f}".format(**info))  # 使用字典解包的方式,保留两位小数

结果如下

The bread's price is 23.20
The bread's price is 23.20
The bread's price is 23.20
The bread's price is 23.20
The bread's price is 23.20
四、Reference

https://www.runoob.com/python/python-strings.html

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5700806.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存