Python format 字符串格式化函数

Python format 字符串格式化函数

一、简介

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

二、占位符%表达式方式

1、使用默认位置方式

字符串格式符号用法如下
在这里插入图片描述
举个例子:

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
2、使用字典的方式

使用方法是在%s之间添加需要通过字典来查找的键值
可以通过字典的键值对来指定格式化元素的位置

D = dict(name='Bob', job='dev')
print('%(name)s, %(job)s' %(D))
Bob, dev

三、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

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值