Python 2.6 之前的字符串格式化
当我在 Python 2.5.2 中运行以下代码:
for x in range(1, 11):
print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
我得到:
Traceback (most recent call last):
File "<pyshell#9>", line 2, in <module>
print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
AttributeError: 'str' object has no attribute 'format'
我不明白这个问题。
从 dir('hello')
的结果来看,没有 format
这个属性。
我该怎么解决这个问题呢?
6 个回答
8
我觉得这是Python 3.0的一个特性,虽然在2.6版本中也有。不过如果你用的是更早的Python版本,那种字符串格式化的方法就不能用了。
如果你想打印格式化的字符串,通常可以通过%
这个符号来使用Python的printf风格语法。例如:
print '%.2f' % some_var
38
你的示例代码看起来是为 Python 2.6 或更高版本写的,因为在这个版本中引入了 str.format 方法。
如果你使用的是 2.6 之前的 Python 版本,可以使用 百分号(%)运算符来把一系列值插入到格式字符串中:
for x in range(1, 11):
print '%2d %3d %4d' % (x, x*x, x*x*x)
你还应该知道,这个运算符可以通过 名称 从一个映射中插入值,而不仅仅是通过位置参数:
>>> "%(foo)s %(bar)d" % {'bar': 42, 'foo': "spam", 'baz': None}
'spam 42'
结合内置的 vars() 函数返回命名空间的属性作为映射,这样用起来会非常方便:
>>> bar = 42
>>> foo = "spam"
>>> baz = None
>>> "%(foo)s %(bar)d" % vars()
'spam 42'
48
str.format
方法是在 Python 3.0 中引入的,并且也被移植到了 Python 2.6 及之后的版本。