Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。
format():格式化單一值
format() 是內建函數,用來把一個值按照指定的格式轉成字串。注意這跟字串的 str.format() 方法不一樣,內建的 format() 一次只處理一個值。
語法:format(value, format_spec='')基本用法:
# 不指定格式,等同 str()
print(format(42)) # '42'
print(format(3.14)) # '3.14'
# 指定小數位數
print(format(3.14159, '.2f')) # '3.14'
print(format(3.14159, '.4f')) # '3.1416'(四捨五入)數字格式化
format() 最常用在數字的格式化上,支援千分位、百分比、科學記號等:
# 千分位分隔
print(format(1234567, ',')) # '1,234,567'
print(format(1234567.89, ',.2f')) # '1,234,567.89'
# 百分比
print(format(0.756, '.1%')) # '75.6%'
print(format(0.5, '%')) # '50.000000%'
# 科學記號
print(format(1234567, '.2e')) # '1.23e+06'
print(format(0.00123, '.2e')) # '1.23e-03'對齊與填充
format() 可以指定寬度、對齊方式和填充字元:
# 靠右對齊(預設)
print(format(42, '>10')) # ' 42'
# 靠左對齊
print(format(42, '<10')) # '42 '
# 置中對齊
print(format(42, '^10')) # ' 42 '
# 自訂填充字元
print(format(42, '*>10')) # '********42'
print(format(42, '0>10')) # '0000000042'
print(format('Hi', '-^10')) # '----Hi----'進位轉換
format() 也可以把整數轉成不同進位的表示:
num = 255
print(format(num, 'b')) # '11111111'(二進位)
print(format(num, 'o')) # '377'(八進位)
print(format(num, 'x')) # 'ff'(十六進位小寫)
print(format(num, 'X')) # 'FF'(十六進位大寫)
# 加上前綴
print(format(num, '#b')) # '0b11111111'
print(format(num, '#o')) # '0o377'
print(format(num, '#x')) # '0xff'format() vs f-string
format() 和 f-string 的格式規則是一樣的,但使用場景不同:
price = 1234.5
# 這三種寫法結果一樣
print(format(price, ',.2f')) # '1,234.50'
print(f'{price:,.2f}') # '1,234.50'
print('{:,.2f}'.format(price)) # '1,234.50'
# format() 的好處:格式字串可以是變數
fmt = ',.2f'
print(format(price, fmt)) # '1,234.50'format() 的優勢在於格式規則可以動態指定,f-string 的格式部分必須寫死。
小小綜合例子
來做一個簡單的數字格式化展示器,把同一個數字用各種格式顯示:
# 數字格式化展示器
def show_formats(num):
print(f'數字:{num}')
print('=' * 35)
formats = [
('預設', ''),
('小數 2 位', '.2f'),
('千分位', ','),
('千分位+小數', ',.2f'),
('百分比', '.1%'),
('科學記號', '.2e'),
('靠右 15 字元', '>15,.2f'),
('靠左 15 字元', '<15,.2f'),
('零填充 15 字元', '0>15,.2f'),
]
for name, fmt in formats:
result = format(num, fmt)
print(f'{name:<15} | {fmt:<15} | [{result}]')
show_formats(12345.678)
# 輸出:
# 數字:12345.678
# ===================================
# 預設 | | [12345.678]
# 小數 2 位 | .2f | [12345.68]
# 千分位 | , | [12,345.678]
# 千分位+小數 | ,.2f | [12,345.68]
# 百分比 | .1% | [1234567.8%]
# 科學記號 | .2e | [1.23e+04]
# 靠右 15 字元 | >15,.2f | [ 12,345.68]
# 靠左 15 字元 | <15,.2f | [12,345.68 ]
# 零填充 15 字元 | 0>15,.2f | [00000012,345.68]