日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python?format字符串格式化函數的使用_python

作者:木心 ? 更新時間: 2022-03-28 編程語言

一、簡介

從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://blog.csdn.net/qq_44940689/article/details/122394153

欄目分類
最近更新