Python基礎(chǔ)指南之字符串格式化format()方法用法詳解
一、開(kāi)篇:百分號(hào)的升級(jí)版
上一篇文章我們學(xué)習(xí)了最古老的百分號(hào) % 格式化。今天的主角是 str.format()——Python 2.6引入的"二代"格式化方式。它在功能上遠(yuǎn)超百分號(hào),曾是Python官方推薦的字符串格式化方法,直到f-string的出現(xiàn)。
雖然f-string現(xiàn)在更受歡迎,但 format() 有一個(gè)不可替代的優(yōu)勢(shì):模板可以預(yù)先定義,然后反復(fù)使用。這在配置文件、郵件模板、日志格式等場(chǎng)景中至關(guān)重要。另外,很多老項(xiàng)目的代碼都是用 format() 寫的,你需要能讀懂和修改它們。
二、format() 的基本語(yǔ)法
2.1 三種調(diào)用方式
# 方式一:按位置(最常用)
text = '{} {} {}'.format('Python', '是', '優(yōu)雅的')
print(text) # Python 是 優(yōu)雅的
# 方式二:按索引(從0開(kāi)始)
text = '{0} {1} {0}'.format('Hello', 'World')
print(text) # Hello World Hello
# 方式三:按名稱
text = '{name}今年{age}歲'.format(name='小明', age=25)
print(text) # 小明今年25歲
2.2 占位符 {}
# 空花括號(hào)——按順序填空
print('{}, {}, {}'.format('a', 'b', 'c')) # a, b, c
# 帶索引——指定使用哪個(gè)參數(shù)(可以重復(fù)、打亂順序)
print('{2}, {0}, {1}'.format('a', 'b', 'c')) # c, a, b
print('{0}{0}{0}'.format('哈')) # 哈哈哈
# 帶名稱——最清晰的寫法
print('{title}:《{name}》'.format(title='書籍', name='Python入門'))
# 書籍:《Python入門》
三、格式化控制
3.1 對(duì)齊與寬度
# 基本格式:{:[填充字符][對(duì)齊方式][寬度]}
# 右對(duì)齊(默認(rèn),數(shù)字常用)
print('{:>10}'.format('hello')) # ' hello'
# 左對(duì)齊(文本常用)
print('{:<10}'.format('hello')) # 'hello '
# 居中對(duì)齊
print('{:^10}'.format('hello')) # ' hello '
# 帶填充字符
print('{:*>10}'.format('hello')) # '*****hello'
print('{:*<10}'.format('hello')) # 'hello*****'
print('{:*^10}'.format('hello')) # '**hello***'
# 數(shù)字的填充(常用補(bǔ)零)
print('{:0>5d}'.format(42)) # '00042'
print('{:0>8d}'.format(2024)) # '00002024'
3.2 數(shù)字格式化
# 整數(shù)
print('{:d}'.format(42)) # 42
print('{:5d}'.format(42)) # ' 42'(右對(duì)齊,寬度5)
print('{:+d}'.format(42)) # +42(顯示正號(hào))
print('{:+d}'.format(-42)) # -42
print('{:,}'.format(1234567890)) # 1,234,567,890(千分位)
# 浮點(diǎn)數(shù)
pi = 3.14159265
print('{:f}'.format(pi)) # 3.141593(默認(rèn)6位)
print('{:.2f}'.format(pi)) # 3.14
print('{:.4f}'.format(pi)) # 3.1416
print('{:10.2f}'.format(pi)) # ' 3.14'(寬度10,2位小數(shù))
print('{:010.2f}'.format(pi)) # '0000003.14'(補(bǔ)零)
# 科學(xué)計(jì)數(shù)法
print('{:e}'.format(1234567)) # 1.234567e+06
print('{:.2e}'.format(1234567)) # 1.23e+06
print('{:E}'.format(1234567)) # 1.234567E+06
# 百分比
print('{:.1%}'.format(0.8567)) # 85.7%
print('{:.2%}'.format(0.12345)) # 12.35%
# 進(jìn)制轉(zhuǎn)換
print('{:b}'.format(255)) # 11111111(二進(jìn)制)
print('{:o}'.format(255)) # 377(八進(jìn)制)
print('{:x}'.format(255)) # ff(十六進(jìn)制小寫)
print('{:X}'.format(255)) # FF(十六進(jìn)制大寫)
print('{:#x}'.format(255)) # 0xff(帶前綴)
print('{:#b}'.format(255)) # 0b11111111
3.3 完整的格式化規(guī)范
format()的完整格式說(shuō)明符語(yǔ)法:{:[填充字符][對(duì)齊][符號(hào)][#][0][寬度][分組選項(xiàng)][.精度][類型]}
# 逐一演示
number = 1234567.89
# 填充字符 + 對(duì)齊 + 寬度
print('{:*>15}'.format('標(biāo)題')) # '************標(biāo)題'
# 符號(hào):+ 強(qiáng)制顯示正號(hào),- 只顯示負(fù)號(hào)(默認(rèn)),空格 正數(shù)前留空格
print('{:+}'.format(42)) # +42
print('{:-}'.format(42)) # 42
print('{: }'.format(42)) # ' 42'
print('{: }'.format(-42)) # -42
# 分組選項(xiàng):, 或 _ 作為千分位
print('{:,}'.format(1234567)) # 1,234,567
print('{:_}'.format(1234567)) # 1_234_567
# 全部組合:填充補(bǔ)零+符號(hào)+千分位+精度
print('{:0=+15,.2f}'.format(number))
# '+001,234,567.89'
四、高級(jí)用法
4.1 訪問(wèn)列表和字典
# 訪問(wèn)列表元素(索引)
fruits = ['蘋果', '香蕉', '橘子']
print('我喜歡吃{0[0]}、{0[1]}和{0[2]}'.format(fruits))
# 我喜歡吃蘋果、香蕉和橘子
# 訪問(wèn)字典元素
person = {'name': '小明', 'age': 25, 'city': '北京'}
print('{name},{age}歲,來(lái)自{city}'.format(**person))
# 小明,25歲,來(lái)自北京
# **person 將字典解包為關(guān)鍵字參數(shù)
# 直接使用字典鍵
print('{0[name]}今年{0[age]}歲'.format(person))
# 訪問(wèn)對(duì)象屬性
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 5)
print('點(diǎn)坐標(biāo):({0.x}, {0.y})'.format(p)) # 點(diǎn)坐標(biāo):(3, 5)
4.2 嵌套字段
# 格式化參數(shù)可以動(dòng)態(tài)指定
# 例如:寬度和精度從變量中讀取
width = 10
precision = 3
# 用嵌套花括號(hào)
print('{:{}.{}f}'.format(3.14159, width, precision))
# ' 3.142'
# 更清晰的寫法
print('{value:{width}.{precision}f}'.format(
value=3.14159, width=10, precision=3
))
# 動(dòng)態(tài)選擇格式化類型
def format_value(value, fmt_type):
"""根據(jù)類型動(dòng)態(tài)格式化值"""
return '{0:{1}}'.format(value, fmt_type)
print(format_value(255, 'x')) # ff
print(format_value(255, 'b')) # 11111111
print(format_value(255, '#X')) # 0XFF
print(format_value(0.85, '.1%')) # 85.0%
4.3 日期時(shí)間格式化
from datetime import datetime
now = datetime(2025, 5, 30, 14, 30, 45)
# 使用datetime對(duì)象的strftime在format中
print('{:%Y-%m-%d %H:%M:%S}'.format(now))
# 2025-05-30 14:30:45
print('{:%Y年%m月%d日 %H時(shí)%M分}'.format(now))
# 2025年05月30日 14時(shí)30分
# 各種日期格式
formats = [
'{:%Y-%m-%d}',
'{:%y/%m/%d}',
'{:%B %d, %Y}',
'{:%A}',
'{:%H:%M:%S}',
]
for fmt in formats:
print(fmt.format(now))
4.4 轉(zhuǎn)義花括號(hào)
# 如何在format字符串中輸出花括號(hào)本身?
# 答案:雙寫花括號(hào)
print('{{hello}}'.format()) # {hello}
print('{{0}} 的值是 {0}'.format(42)) # {0} 的值是 42
print('{{{0}}}'.format('Python')) # {Python}
# 在JSON模板中很有用
json_template = '{{"name": "{name}", "age": {age}}}'
result = json_template.format(name='小明', age=25)
print(result) # {"name": "小明", "age": 25}
五、format() 實(shí)戰(zhàn)應(yīng)用
5.1 表格打印
def print_table(headers, rows):
"""使用format打印對(duì)齊的表格"""
# 計(jì)算每列的寬度
col_widths = [len(h) for h in headers]
# 格式化行的單元格
formatted_rows = []
for row in rows:
formatted = [str(cell) for cell in row]
formatted_rows.append(formatted)
for i, cell in enumerate(formatted):
col_widths[i] = max(col_widths[i], len(cell))
# 構(gòu)建格式字符串
format_str = ' | '.join('{:<%d}' % w for w in col_widths)
# 打印表頭
print(format_str.format(*headers))
# 打印分隔線
print('-+-'.join('-' * w for w in col_widths))
# 打印數(shù)據(jù)行
for row in formatted_rows:
print(format_str.format(*row))
headers = ['姓名', '年齡', '城市', '職業(yè)']
rows = [
('小明', 25, '北京', '軟件工程師'),
('小紅', 23, '上海', 'UI設(shè)計(jì)師'),
('小剛', 26, '廣州', '數(shù)據(jù)分析師'),
]
print_table(headers, rows)
5.2 生成SQL語(yǔ)句
def build_select_query(table, columns=None, where=None, order_by=None, limit=None):
"""用format構(gòu)建SQL查詢"""
if columns:
col_str = ', '.join(columns)
else:
col_str = '*'
query = 'SELECT {cols} FROM {table}'.format(cols=col_str, table=table)
if where:
conditions = ' AND '.join('{k} = %({k})s'.format(k=k) for k in where)
query += ' WHERE ' + conditions
if order_by:
query += ' ORDER BY ' + order_by
if limit:
query += ' LIMIT {:d}'.format(limit)
return query
query = build_select_query(
'users',
columns=['id', 'name', 'email'],
where=['status', 'role'],
order_by='created_at DESC',
limit=10
)
print(query)
5.3 進(jìn)度條
import time
def progress_bar(total, prefix='', suffix='', length=50):
"""使用format的動(dòng)態(tài)寬度顯示進(jìn)度條"""
def print_progress(iteration):
percent = '{:.1f}'.format(100 * iteration / total)
filled = int(length * iteration // total)
bar = '█' * filled + '-' * (length - filled)
print('\r{} |{}| {}% {}'.format(prefix, bar, percent, suffix),
end='', flush=True)
print_progress(0)
for i in range(1, total + 1):
time.sleep(0.02)
print_progress(i)
print()
progress_bar(100, prefix='下載中:', suffix='完成', length=40)
六、format() 的性能
import time
name = 'Python'
version = 3.12
year = 2025
# 三種方式性能對(duì)比(執(zhí)行100萬(wàn)次)
# % 格式化
start = time.perf_counter()
for _ in range(1000000):
result = '%s %s 發(fā)布于 %d' % (name, version, year)
elapsed_pct = time.perf_counter() - start
print(f'% 格式化:{elapsed_pct:.3f}秒')
# format()
start = time.perf_counter()
for _ in range(1000000):
result = '{} {} 發(fā)布于 {}'.format(name, version, year)
elapsed_format = time.perf_counter() - start
print(f'format(): {elapsed_format:.3f}秒')
# f-string (最快)
start = time.perf_counter()
for _ in range(1000000):
result = f'{name} {version} 發(fā)布于 {year}'
elapsed_f = time.perf_counter() - start
print(f'f-string:{elapsed_f:.3f}秒')
性能排序:f-string > %格式化 > format()。但在絕大多數(shù)場(chǎng)景下,這個(gè)性能差異可以忽略不計(jì)??勺x性比這點(diǎn)性能重要得多。
七、format() vs f-string:何時(shí)該用format()
雖然f-string更簡(jiǎn)潔更快,但以下場(chǎng)景還是得用(或更適合用)format():
# 場(chǎng)景一:模板復(fù)用
# 你需要多次使用同一個(gè)模板填充不同的值
template = '尊敬的{name},您的訂單{order_id}已{status}。'
messages = [
template.format(name='小明', order_id='001', status='發(fā)貨'),
template.format(name='小紅', order_id='002', status='處理中'),
template.format(name='小剛', order_id='003', status='完成'),
]
for msg in messages:
print(msg)
# 場(chǎng)景二:配置文件中的模板
# 從配置文件讀取模板字符串
email_template = """
Hello {username},
Your account balance is ${balance:.2f}.
Last login: {last_login:%Y-%m-%d}
Best regards,
{company}
"""
# 在運(yùn)行時(shí)填充
email = email_template.format(
username='小明',
balance=1520.5,
last_login=datetime.now(),
company='Python學(xué)習(xí)平臺(tái)'
)
print(email)
# 場(chǎng)景三:動(dòng)態(tài)構(gòu)建格式字符串
# 用戶可以選擇顯示格式
def format_number(number, style='decimal'):
formats = {
'decimal': '{:,}',
'scientific': '{:.2e}',
'hex': '{:#x}',
'binary': '{:#b}',
'percent': '{:.2%}',
}
fmt_string = formats.get(style, '{}')
return fmt_string.format(number)
# 場(chǎng)景四:需要支持Python 3.5及以下版本
# f-string是Python 3.6引入的
八、本篇小結(jié)
str.format() 是功能豐富的字符串格式化方式:
- 三種傳參方式:按位置
{}、按索引{0}、按名稱{name} - 對(duì)齊與填充:
{:<10}左對(duì)齊、{:>10}右對(duì)齊、{:^10}居中、{:*^10}帶填充 - 數(shù)字格式化:
{:.2f}小數(shù)位、{:,}千分位、{:b}二進(jìn)制、{:.1%}百分比 - 訪問(wèn)容器:
{0[0]}訪問(wèn)列表、{name}訪問(wèn)字典 - 模板復(fù)用:format()最獨(dú)特的優(yōu)勢(shì)——模板可預(yù)定義重復(fù)使用
f-string是新代碼的首選,但理解format()對(duì)于閱讀和維護(hù)代碼庫(kù)至關(guān)重要。下一篇我們學(xué)習(xí)Python最現(xiàn)代、最推薦的字符串格式化方式——f-string。
以上就是Python基礎(chǔ)指南之字符串格式化format()方法用法詳解的詳細(xì)內(nèi)容,更多關(guān)于Python字符串格式化的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Pycharm的終端(Terminal)中切換到當(dāng)前項(xiàng)目所在的虛擬環(huán)境方式
在PyCharm中切換到當(dāng)前項(xiàng)目所在虛擬環(huán)境的步驟:1.點(diǎn)擊底部終端標(biāo)簽;2.在終端右上角選擇命令提示符;3.環(huán)境切換為項(xiàng)目虛擬環(huán)境,若想默認(rèn)顯示項(xiàng)目虛擬環(huán)境,可以在設(shè)置中更改Shell路徑2026-02-02
python利用元類和描述器實(shí)現(xiàn)ORM模型的詳細(xì)步驟
Python中的類與數(shù)據(jù)庫(kù)之間的映射,對(duì)數(shù)據(jù)的操作就不用編寫SQL語(yǔ)言了,因?yàn)槎挤庋b好了,比如你想插入一條數(shù)據(jù),你就直接創(chuàng)建一個(gè)對(duì)象即可,下面通過(guò)本文學(xué)習(xí)下python利用元類和描述器實(shí)現(xiàn)ORM模型的詳細(xì)步驟,感興趣的朋友一起看看吧2021-11-11
python列表使用實(shí)現(xiàn)名字管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python列表使用實(shí)現(xiàn)名字管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01
tensorflow實(shí)現(xiàn)二維平面模擬三維數(shù)據(jù)教程
今天小編就為大家分享一篇tensorflow實(shí)現(xiàn)二維平面模擬三維數(shù)據(jù)教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
python unix時(shí)間戳轉(zhuǎn)換毫秒的實(shí)現(xiàn)
Unix時(shí)間戳是一種常見(jiàn)的時(shí)間表示方式,本文主要介紹了python unix時(shí)間戳轉(zhuǎn)換毫秒的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2024-01-01
win10系統(tǒng)下Anaconda3安裝配置方法圖文教程
這篇文章主要為大家詳細(xì)介紹了win10系統(tǒng)下Anaconda3安裝配置方法圖文教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09
Python數(shù)據(jù)可視化編程通過(guò)Matplotlib創(chuàng)建散點(diǎn)圖代碼示例
這篇文章主要介紹了Python數(shù)據(jù)可視化編程通過(guò)Matplotlib創(chuàng)建散點(diǎn)圖實(shí)例,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
python 解決flask uwsgi 獲取不到全局變量的問(wèn)題
今天小編就為大家分享一篇python 解決flask uwsgi 獲取不到全局變量的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12

