如何为所有少于两位数的数字显示前导零?
1 → 01 10 → 10 100 → 100
要在 Python 中为所有少于两位数的数字显示前导零,可以使用字符串格式化方法
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)
所有这些方法都会产生所需的输出,即在少于两位数的数字前添加一个零。
您可以使用str.zfill:
str.zfill
print(str(1).zfill(2)) print(str(10).zfill(2)) print(str(100).zfill(2))
输出:
01 10 100