5

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

Community
  • 1
  • 1
JS.
  • 13,077
  • 11
  • 57
  • 72
  • Duplicate of [Printing tuple with string formatting in Python](http://stackoverflow.com/questions/1455602/printing-tuple-with-string-formatting-in-python). If you realize your question is a duplicate, flag it "it doesn't belong here -> exact duplicate", don't just add a link to the question. – agf Sep 22 '11 at 22:03

5 Answers5

10

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.

Andrew Clark
  • 192,132
  • 30
  • 260
  • 294
2

You can do this:

>>> print("my_test = %r" % str(my_test))
my_test = 'Test(this=1, that=2)'
infrared
  • 3,360
  • 2
  • 22
  • 37
2

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,))
Avaris
  • 34,325
  • 7
  • 75
  • 71
0

The earlier answers are valid but here's an option if you don't care to print the name. It's a one-liner devised to pretty print only the contents of a named tuple of arbitrary length. Given a named tuple assigned to "named_tuple" the below yields a comma-delineated string of key=value pairs:

', '.join(['{0}={1}'.format(k, getattr(named_tuple, k)) for k in named_tuple._fields])
user1034632
  • 51
  • 2
  • 4
0

As now documented at 4.7.2. printf-style String Formatting, the % string formatting or interpolation operator is problematic:

The [printf-style string formatting operations] exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the str.format() interface helps avoid these errors

So for example you can now do:

from collections import namedtuple
Test = namedtuple('Test', ['this', 'that'])
my_test = Test(this=1, that=2)
print("my_test = {0!r}".format(my_test))
nealmcb
  • 10,965
  • 6
  • 61
  • 85