Printing named tuples

JS. picture JS. · Sep 22, 2011 · Viewed 12.8k times · Source

In Python 2.7.1 I can create a named tuple:

from collections import namedtuple
Test = namedtuple('Test', ['this', 'that'])

I can populate it:

my_test = Test(this=1, that=2)

And I can print it like this:

print(my_test)

Test(this=1, that=2)

but why can't I print it like this?

print("my_test = %r" % my_test)

TypeError: not all arguments converted during string formatting

Edit: I should have known to look at Printing tuple with string formatting in Python

Answer

Andrew Clark picture Andrew Clark · Sep 22, 2011

Since my_test is a tuple, it will look for a % format for each item in the tuple. To get around this wrap it in another tuple where the only element is my_test:

print("my_test = %r" % (my_test,))

Don't forget the comma.