在Python 2.7中,我想使用字符串格式化模板打印日期时间对象。但是不知何故,使用左/右对齐不能正确地打印字符串。
这将导致以下结果:
有没有什么技巧可以使用字符串格式模板打印datetime对象?当我将datetime对象强制转换为str()时,似乎可以工作。
import datetime
dt = datetime.datetime(2013, 6, 26, 9, 0)
l = [dt, dt]
template = "{0:>25} {1:>25}" # right justify
print template.format(*l) #print items in the list using template
这将导致以下结果:
>25 >25
代替
2013-06-26 09:00:00 2013-06-26 09:00:00
有没有什么技巧可以使用字符串格式模板打印datetime对象?当我将datetime对象强制转换为str()时,似乎可以工作。
print template.format(str(l[0]), str(l[1]))
但是我不想这样做,因为我正在尝试打印一系列值,其中一些不是字符串。制作字符串模板的整个目的是打印列表中的项目。
我是否对字符串格式有所遗漏,或者这似乎是Python的错误?
解决方案
@mgilson指出了我在文档中错过的解决方案。链接
当前支持两个转换标志:'!s' 调用 str() 函数,'!r' 调用 repr() 函数。
以下是一些示例:
"Harold's a clever {0!s}" # Calls str() on the argument first
"Bring out the holy {name!r}" # Calls repr() on the argument first