就像这样你可以如何用 0 填充格式字符串
for i in range(10):
zeropad = "Value is{:03}.".format(i)
print(zeropad)
你得到的结果是
Value is 000
Value is 001
等等...
那么,我怎样才能用 f 弦做同样的事情呢?
我尝试使用 .zfill() 函数,但这也不起作用
for i in range(1, 11):
sentence = f"The value is {i(zfill(3))}."
print(sentence)`
这会产生错误
Traceback (most recent call last):
File "main.py", line 2, in <module>
sentence = f"The value is {i.zfill(3)}."
AttributeError: 'int' object has no attribute 'zfill'
修复你的方法:
for i in range(1, 11):
sentence = f"The value is {str(i).zfill(3)}."
print(sentence)
f 弦方法
for i in range(1, 11):
sentence = f"The value is {i:03}."
print(sentence)