首頁 >後端開發 >Python教學 >如何在 Python 中為數字字串新增前導零?

如何在 Python 中為數字字串新增前導零?

Susan Sarandon
Susan Sarandon原創
2024-12-27 14:24:10456瀏覽

How Can I Add Leading Zeros to Numeric Strings in Python?

零填充數字字串

要將前導零添加到數字字串以增加其長度,Python 中可以採用多種方法:

填充字串:

對於字串填充,使用 zfill方法:

n = '4'
print(n.zfill(3))  # Output: 004

填充數字:

可以使用各種方法墊數字:

  • f 字串( Python >= 3.6首選):
n = 4
print(f'{n:03}')  # Output: 004
  • 模運算子:
print('%03d' % n)  # Output: 004
  • 化函數(Python >= 2.6):
print(format(n, '03'))  # Output: 004
print('{0:03d}'.format(n))  # Output: 004
print('{foo:03d}'.format(foo=n))  # Output: 004
  • format_spec 迷你語言(Python >= 2.7 Python 3):
print('{:03d}'.format(n))  # Output: 004

>有關更多詳細信息,請參閱字串格式化文件。

以上是如何在 Python 中為數字字串新增前導零?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn