在Python中,如何在将int转换为字符串时指定格式?
更确切地说,我希望我的格式添加前导零以具有恒定长度的字符串.例如,如果常量长度设置为4:
当整数大于允许给定长度(在我的示例中为9999)时,我对行为没有约束.
我怎么能用Python做到这一点?
Sri*_*aju 12
你可以使用类的zfill功能str.像这样 -
>>> str(165).zfill(4)
'0165'
Run Code Online (Sandbox Code Playgroud)
也可以%04d像其他人建议的那样做.但我认为这更像是pythonic的做法...
使用 python3 格式和新的 3.6 f"" 符号:
>>> i = 5
>>> "{:4n}".format(i)
' 5'
>>> "{:04n}".format(i)
'0005'
>>> f"{i:4n}"
' 5'
>>> f"{i:04n}"
'0005'
Run Code Online (Sandbox Code Playgroud)