Python中format格式化的用法及說(shuō)明
可以通過(guò)下面幾種方式來(lái)實(shí)現(xiàn)
1、使用{}
作為占位符,通過(guò)索引來(lái)指定要替換的參數(shù),如:
# 替換第一個(gè)參數(shù) "Hello {}, Welcome to Python world!".format("Tom") # 替換第二個(gè)參數(shù) "Hello {1}, Welcome to Python world! I'm {0}".format("Tom", "Alice")
2、使用{}
作為占位符,通過(guò)參數(shù)名來(lái)指定要替換的參數(shù),如:
# 替換name參數(shù) "Hello {name}, Welcome to Python world!".format(name="Tom") # 替換name和age參數(shù) "Hello {name}, Welcome to Python world! I'm {age}".format(name="Tom", age=20)
3、使用{}
作為占位符,通過(guò)指定參數(shù)位置和類型來(lái)進(jìn)行格式化,如:
# 使用:指定參數(shù)類型和格式,d表示整數(shù),f表示浮點(diǎn)數(shù),s表示字符串 "Hello {0:s}, Welcome to Python world! I'm {1:d} years old".format("Tom", 20) "Hello {0:s}, Welcome to Python world! I'm {1:f} meters tall".format("Tom", 1.75)
有以下幾個(gè)注意事項(xiàng)
1、如果使用了{}
作為占位符,那么參數(shù)中不能出現(xiàn){}
字符,否則會(huì)拋出異常,應(yīng)該使用{{}}來(lái)表示{字符,如:
# 錯(cuò)誤用法 "Hello {name}, Welcome to Python world! I'm from {{China}}".format(name="Tom") # 正確用法 "Hello {name}, Welcome to Python world! I'm from {country}".format(name="Tom", country="China")
2、在format函數(shù)中,如果指定了參數(shù)名或位置,那么參數(shù)的順序并不重要,如:
# 不同的參數(shù)順序 "Hello {0}, Welcome to Python world! I'm {1} years old".format(20, "Tom") "Hello {1}, Welcome to Python world! I'm {0} years old".format(20, "Tom")
3、在format函數(shù)中,如果使用了參數(shù)名或位置,那么在調(diào)用時(shí),必須保證提供了對(duì)應(yīng)的參數(shù),否則會(huì)拋出異常,如:
# 錯(cuò)誤用法,沒(méi)有提供name參數(shù) "Hello {name}, Welcome to Python world!".format() # 正確用法 "Hello {name}, Welcome to Python world!".format(name="Tom")
4、在format函數(shù)中,如果沒(méi)有使用參數(shù)名或位置,那么參數(shù)的順序必須與占位符的順序一致,否則會(huì)拋出異常,如:
# 錯(cuò)誤用法,參數(shù)順序不一致 "Hello {}, Welcome to Python world! I'm {} years old".format(20, "Tom") # 正確用法 "Hello {}, Welcome to Python world! I'm {} years old".format("Tom", 20)
5、在format函數(shù)中,如果使用了參數(shù)名或位置,那么在調(diào)用時(shí)可以提供多余的參數(shù),這些參數(shù)不會(huì)被使用,如:
# 提供了多余的參數(shù) "Hello {name}, Welcome to Python world!".format(name="Tom", age=20)
6、在format函數(shù)中,可以使用**kwargs
參數(shù)將一個(gè)字典中的所有鍵值對(duì)作為參數(shù)傳遞給format函數(shù),如:
# 使用**kwargs傳遞參數(shù) params = {"name": "Tom", "age": 20} "Hello {name}, Welcome to Python world! I'm {age} years old".format(**params)
7、在format函數(shù)中,如果使用了{}
作為占位符,那么可以使用format_map
函數(shù)來(lái)替換占位符,其中format_map函數(shù)的參數(shù)必須是一個(gè)映射對(duì)象,如:
# 使用format_map函數(shù)替換占位符 params = {"name": "Tom", "age": 20} "Hello {name}, Welcome to Python world! I'm {age} years old".format_map(params)
8、在format函數(shù)中,如果需要對(duì)字符串進(jìn)行多次替換,那么可以使用format_map函數(shù),它可以直接在字符串上調(diào)用,而不用重新創(chuàng)建一個(gè)新的字符串,如:
# 使用format_map函數(shù)進(jìn)行多次替換 params = {"name": "Tom", "age": 20} s = "Hello {name}, Welcome to Python world! I'm {age} years old" new = s.format_map(params) print(new) # 更新參數(shù),并繼續(xù)替換 params["age"] = 21 new_2 = s.format_map(params) print(new_2)
9、在format函數(shù)中,如果使用了{}
作為占位符,那么可以使用vars函數(shù)
自動(dòng)將一個(gè)對(duì)象的屬性作為參數(shù)傳遞給format函數(shù),如:
# 使用vars函數(shù)自動(dòng)將一個(gè)對(duì)象的屬性作為參數(shù)傳遞給format函數(shù) class Person: def __init__(self, name, age): self.name = name self.age = age p = Person("Tom", 20) "Hello {name}, Welcome to Python world! I'm {age} years old".format(**vars(p))
10、在format函數(shù)中,如果使用了{}
作為占位符,那么可以使用Template類
來(lái)實(shí)現(xiàn)字符串的模板化,可以通過(guò)$來(lái)指定參數(shù)名,并通過(guò)safe_substitute函數(shù)
來(lái)替換占位符,如:
# 使用Template類實(shí)現(xiàn)字符串的模板化 from string import Template s = Template("Hello $name, Welcome to Python world! I'm $age years old") s.safe_substitute(name="Tom", age=20)
11、在format函數(shù)中,如果使用了{}
作為占位符,那么可以通過(guò)f-string
來(lái)實(shí)現(xiàn)字符串的替換,f-string必須使用Python3.6或更高版本
,它支持在字符串中直接使用變量名,并通過(guò){}
包裹,如:
# 使用f-string實(shí)現(xiàn)字符串的替換 name = "Tom" age = 20 f"Hello {name}, Welcome to Python world! I'm {age} years old"
12、在format函數(shù)中,如果需要對(duì)字符串進(jìn)行格式化,那么可以使用format函數(shù)的相關(guān)參數(shù),如align、width、precision等來(lái)控制字符串的對(duì)齊方式、寬度、精度等,如:
# 使用format函數(shù)的相關(guān)參數(shù)進(jìn)行格式化 name = "Tom" age = 20 # 左對(duì)齊,寬度為20,小數(shù)點(diǎn)后保留2位 "Hello {0:<20.2f}".format(name, age) # 右對(duì)齊,寬度為20,小數(shù)點(diǎn)后保留2位 "Hello {0:>20.2f}".format(name, age) # 居中對(duì)齊,寬度為20,小數(shù)點(diǎn)后保留2位 "Hello {0:^20.2f}".format(name, age)
13、在format函數(shù)中,如果需要對(duì)數(shù)字進(jìn)行格式化,那么可以使用format函數(shù)的相關(guān)參數(shù),如:
# 千分位分隔符 "{:,}".format(123456789) # 百分?jǐn)?shù) "{:.2%}".format(0.8) # 科學(xué)計(jì)數(shù)法 "{:.2e}".format(123456789) # 十六進(jìn)制 "{:x}".format(255)
14、在format函數(shù)中,如果需要對(duì)日期時(shí)間進(jìn)行格式化,那么可以使用strftime函數(shù)
來(lái)指定日期時(shí)間的格式化字符串,如:
# 使用strftime函數(shù)格式化日期時(shí)間 from datetime import datetime dt = datetime.now() print(dt) a = dt.strftime("%Y-%m-%d %H:%M:%S") print(a) # 輸出 # 2022-12-09 16:51:09.534693 # 2022-12-09 16:51:09
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
selenium3.0+python之環(huán)境搭建的方法步驟
這篇文章主要介紹了selenium3.0+python之環(huán)境搭建的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02Python基于yaml文件配置logging日志過(guò)程解析
這篇文章主要介紹了Python基于yaml文件配置logging日志過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06python與matlab一些常用函數(shù)互轉(zhuǎn)問(wèn)題
這篇文章主要介紹了python與matlab一些常用函數(shù)互轉(zhuǎn),包括十六進(jìn)制字節(jié)流數(shù)據(jù)的相關(guān)知識(shí),本文通過(guò)示例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2022-12-12Python利用pdfplumber實(shí)現(xiàn)讀取PDF寫(xiě)入Excel
pdfplumber專注PDF內(nèi)容提取,例如文本(位置、字體及顏色等)和形狀(矩形、直線、曲線),還有解析表格的功能。本文主要為大家介紹如何利用pdfplumber實(shí)現(xiàn)讀取PDF寫(xiě)入Excel,需要的可以參考一下2022-06-06使用pandas中的DataFrame數(shù)據(jù)繪制柱狀圖的方法
下面小編就為大家分享一篇使用pandas中的DataFrame數(shù)據(jù)繪制柱狀圖的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04Python2.7環(huán)境Flask框架安裝簡(jiǎn)明教程【已測(cè)試】
這篇文章主要介紹了Python2.7環(huán)境Flask框架安裝方法,結(jié)合實(shí)例形式詳細(xì)分析了Python2.7環(huán)境下安裝Flask框架遇到的問(wèn)題與相關(guān)解決方法、注意事項(xiàng),并給出了一個(gè)基本的測(cè)試示例,需要的朋友可以參考下2018-07-07windows及l(fā)inux環(huán)境下永久修改pip鏡像源的方法
不知道有沒(méi)有人跟我一樣,在剛接觸Linux時(shí)被系統(tǒng)更新源問(wèn)題搞得暈頭轉(zhuǎn)向,不同的Linux更新源配置也是不一樣的,另外由于默認(rèn)安裝時(shí)的源大都是外國(guó)的更新源,速度相對(duì)國(guó)內(nèi)會(huì)慢很多,接下來(lái)本文主要介紹在windows和linux兩種系統(tǒng)環(huán)境中更新系統(tǒng)源的方法。2016-11-11Python?3.11.0下載安裝并使用help查看模塊信息的方法
本文給大家介紹Python?3.11.0下載安裝并使用help查看模塊信息的相關(guān)知識(shí),首先給大家講解了Python?3.11.0下載及安裝緊接著介紹了在命令行使用help查看模塊信息的方法,感興趣的朋友跟隨小編一起看看吧2022-11-11