Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing named tuples

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

like image 580
JS. Avatar asked Sep 22 '11 21:09

JS.


3 Answers

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.

like image 169
Andrew Clark Avatar answered Nov 03 '22 00:11

Andrew Clark


You can do this:

>>> print("my_test = %r" % str(my_test))
my_test = 'Test(this=1, that=2)'
like image 24
infrared Avatar answered Nov 03 '22 00:11

infrared


It's unpacking it as 2 arguments. Compare with:

print("dummy1 = %s, dummy2 = %s" % ("one","two"))

In your case, try putting it in a tuple.

print("my_test = %r" % (my_test,))
like image 33
Avaris Avatar answered Nov 03 '22 00:11

Avaris