Python 3等效'%'字符串运算符

时间:2015-10-27 01:36:26

标签: python

import collections

Thing = collections.namedtuple('thing', 'color rotation direction')

thing1 = Thing(color = 'blue', rotation = 90, direction = 'south')
thing2 = Thing(color = 'green', rotation = -90, direction = 'west')

for t in [ thing1, thing2 ]:
    print('%s-colored thing rotated %d degrees %s' % t)

试图在Python 3中找出Python 2 %字符串格式的模拟。当然上面的print()调用在Python 3中有效,但我一直在努力想弄清楚如何使用format()来完成。

这有效,但似乎不是Pythonic:

print('{}-colored thing rotated {} degrees {}'.format(t[0], t[1], t[2]))

我试过

print('{}-colored thing rotated {} degrees {}'.format(t[:]))

但我得到

IndexError: tuple index out of range

1 个答案:

答案 0 :(得分:4)

print('{:s}-colored thing rotated {:d} degrees {:s}'.format(*t))