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
5
  • 7
    The Python3 equivalent of % string operator is the % string operator. It has not been removed nor deprecated. Commented Oct 27, 2015 at 1: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". Commented Oct 27, 2015 at 1:40
  • My apologies. I thought I read that the % operator was deprecated in Python 3, but clearly I was mistaken. Commented Oct 27, 2015 at 16:37
  • It's ... complicated. stackoverflow.com/questions/13451989/… Commented Oct 27, 2015 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. Commented Oct 27, 2015 at 17:31

1 Answer 1

4
print('{:s}-colored thing rotated {:d} degrees {:s}'.format(*t))
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Very true. I added them because OP's original code used %s and %d.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.