str.zfill(width) -> str
在字串左側填充 '0' 至指定總寬度 width。若字串長度 ≥ width,原樣返回。符號(+/-)會被保留在最左側,零填充在符號之後。
s = "this is string example....wow!!!"
print(s.zfill(40))
# 00000000this is string example....wow!!!
print(s.zfill(50))
# 000000000000000000this is string example....wow!!!
# 帶符號數字
print('+42'.zfill(6)) # +00042
print('-42'.zfill(6)) # -00042
zfill vs rjust vs 格式化| 方法 | 範例 | 輸出 | 備註 |
|---|---|---|---|
zfill(6) | '42'.zfill(6) | '000042' | 專為數字零填充,處理符號 |
rjust(6, '0') | '42'.rjust(6,'0') | '000042' | 通用右對齊填充任意字元 |
format(42, '06d') | format(42, '06d') | '000042' | 格式化規範,功能最強 |
f'{42:06d}' | f'{42:06d}' | '000042' | f-string 現代寫法 |
f'IMG_{i:04d}.jpg' 或 str(i).zfill(4)。f'{h:02d}:{m:02d}:{s:02d}'(比 zfill 更直觀)。str.zfill(width) 專為數字字串左側零填充設計,自動處理正負號。現代代碼多改用 f'{num:0{width}d}' 格式化,語義更豐富、支援對齊/進制/千分位等擴展。理解 zfill 歷史地位,新代碼優先選擇格式化字串。