如何格式化用符号和零填充的整数?

How to format integer padded with both sign and zeros?

我需要在 Python3 中用前导符号和小时(考虑时区偏移)格式化时间:

>>> hour = 2
>>> print("T%02d" % hour)
T02
>>> print("T%+02d" % hour)
T+2

预期结果是T+02

字段包含+字符,需要占到宽度。您希望字段的宽度为 3 个字符:

print("T%+03d" % hour)

演示:

>>> hour = 2
>>> print("T%+03d" % hour)
T+02