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

标签 python python-3.x string-formatting

我需要在 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

关于python - 如何格式化用符号和零填充的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46738255/

相关文章:

python - 为什么不能在 f 弦的大括号内使用反斜杠?我该如何解决这个问题?

python - 如何制作一个为输入表的每一行计算结果的python程序?

Python 3 - 如何使用 python docx 库删除 word 文档上的字母

python - Python 中单个函数连续执行之间的时间

c# - C# 中的 String.Format 不返回修改后的 int 值

python - 如何在配置文件中存储格式化字符串?

python - 在 csv 文件中查找模式

r - 从聚合数据在 Python 中拟合生存模型

python - wxGlade GUI行为问题

python - 使用正则表达式对单词进行排序