小能豆

显示带有前导零的数字

python

如何为所有少于两位数的数字显示前导零?

1    →  01
10   →  10
100  →  100

阅读 64

收藏
2024-06-27

共2个答案

小能豆

要在 Python 中为所有少于两位数的数字显示前导零,可以使用字符串格式化方法

使用 f 字符串(Python 3.6+)

numbers = [1, 10, 100]

formatted_numbers = [f"{num:02}" for num in numbers]

print(formatted_numbers)
# Output: ['01', '10', '100']

使用str.zfill()

numbers = [1, 10, 100]

formatted_numbers = [str(num).zfill(2) for num in numbers]

print(formatted_numbers)
# Output: ['01', '10', '100']

使用str.format()

numbers = [1, 10, 100]

formatted_numbers = ["{:02}".format(num) for num in numbers]

print(formatted_numbers)
# Output: ['01', '10', '100']

使用format()

numbers = [1, 10, 100]

formatted_numbers = [format(num, "02") for num in numbers]

print(formatted_numbers)
# Output: ['01', '10', '100']

例子

以下是如何在完整脚本中应用上述任何一种方法:

numbers = [1, 10, 100]

# Using f-strings
formatted_numbers_f = [f"{num:02}" for num in numbers]
print("Using f-strings:", formatted_numbers_f)

# Using str.zfill()
formatted_numbers_zfill = [str(num).zfill(2) for num in numbers]
print("Using str.zfill():", formatted_numbers_zfill)

# Using str.format()
formatted_numbers_format = ["{:02}".format(num) for num in numbers]
print("Using str.format():", formatted_numbers_format)

# Using format()
formatted_numbers_format_func = [format(num, "02") for num in numbers]
print("Using format():", formatted_numbers_format_func)

所有这些方法都会产生所需的输出,即在少于两位数的数字前添加一个零。

2024-06-27
小能豆

您可以使用str.zfill

print(str(1).zfill(2))
print(str(10).zfill(2))
print(str(100).zfill(2))

输出:

01
10
100
2024-06-27