Python之format格式化函數(shù)使用及說明
Python之format格式化函數(shù)
Python2.6 開始,新增了一種格式化字符串的函數(shù) str.format(),它增強了字符串格式化的功能。
基本語法是通過 {} 和 : 來代替以前的 % 。
format 函數(shù)可以接受不限個參數(shù),位置可以不按順序。
>>>"{} {}".format("hello", "world") # 不設置指定位置,按默認順序
'hello world'
>>> "{0} {1}".format("hello", "world") # 設置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 設置指定位置
'world hello world'
也可以設置參數(shù):
print("網(wǎng)站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com"))
# 通過字典設置參數(shù)
site = {"name": "菜鳥教程", "url": "www.runoob.com"}
print("網(wǎng)站名:{name}, 地址 {url}".format(**site))
# 通過列表索引設置參數(shù)
my_list = ['菜鳥教程', 'www.runoob.com']
print("網(wǎng)站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必須的
輸出結果:
網(wǎng)站名:菜鳥教程, 地址 www.runoob.com
網(wǎng)站名:菜鳥教程, 地址 www.runoob.com
網(wǎng)站名:菜鳥教程, 地址 www.runoob.com
也可以向 str.format() 傳入對象:
class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
print('value 為: {0.value}'.format(my_value)) # "0" 是可選的
輸出結果為:
?value 為: 6?
數(shù)字格式化
下表展示了 str.format() 格式化數(shù)字的多種方法
>>> print("{:.2f}".format(3.1415926));
3.14


例如:
print ("{} 對應的位置是 {{0}}".format("runoob"))
輸出結果:
runoob 對應的位置是 {0}?
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python利用pptx操作PPT實現(xiàn)幻燈片的刪除與替換
這篇文章主要為大家詳細介紹了python如何使用pptx庫實現(xiàn)操作PPTx幻燈片文件刪除并替換圖片,文中的示例代碼講解詳細,感興趣的可以嘗試一下2023-02-02
python:解析requests返回的response(json格式)說明
這篇文章主要介紹了python:解析requests返回的response(json格式)說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python3 適合初學者學習的銀行賬戶登錄系統(tǒng)實例
下面小編就為大家?guī)硪黄狿ython3 適合初學者學習的銀行賬戶登錄系統(tǒng)實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08

