0
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)

Trying to figure out the analogue of Python 2 % string formatting in Python 3. Of course the print() call above works in Python 3, but I've been struggling trying to figure out how to do it using format().

This works, but does not seem very Pythonic:

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

I tried

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

but I get

IndexError: tuple index out of range
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Tinman
  • 3
  • 1
  • 7
    The Python3 equivalent of `%` string operator is the `%` string operator. It has not been removed nor deprecated. – Robᵩ Oct 27 '15 at 01:38
  • 1
    Why are you asking for an equivalent to something that hasn't been removed or deprecated? If you want to do it with `format`, then do it with `format`, but `format` is *not* "the equivalent of the `%` operator". – Mark Reed Oct 27 '15 at 01:40
  • My apologies. I thought I read that the % operator was deprecated in Python 3, but clearly I was mistaken. – Tinman Oct 27 '15 at 16:37
  • It's ... complicated. http://stackoverflow.com/questions/13451989/pythons-many-ways-of-string-formatting-are-the-older-ones-going-to-be-deprec – Robᵩ Oct 27 '15 at 16:50
  • Thank you, Robᵩ! So it's safe to say that format() is preferred, even though the % operator has not been deprecated. I'll use `format(*t)` as suggested below. – Tinman Oct 27 '15 at 17:31

1 Answers1

4
print('{:s}-colored thing rotated {:d} degrees {:s}'.format(*t))
Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • 2
    Note that the `:s` and `:d` are optional. OP's original version with the `{}` would have worked fine with the `*` operator on the tuple argument. – Mark Reed Oct 27 '15 at 01:42
  • Very true. I added them because OP's original code used `%s` and `%d`. – Robᵩ Oct 27 '15 at 01:44