1

I have a Python variable (database record) that prints as follows:

((79321L, Decimal('11.56125119')),)

What is the best way to print these two values? I want to do something like this:

print("Count: {}, Result: {}".format(cur.fetchall()))
MountainX
  • 6,217
  • 8
  • 52
  • 83
  • 1
    If you're only expecting a single row as a result, then just use `fetchone()` instead and then you don't have to worry about unpacking this... – Jon Clements Feb 11 '14 at 02:07

4 Answers4

2

The left side unpacking needs to match the structure of the right side. So this will work:

((x, y),) = ((79321L, Decimal('11.56125119')),)

You have a single-item tuple whose contents is a two-item tuple

mhlester
  • 22,781
  • 10
  • 52
  • 75
2
In [10]: a=((79321L, Decimal('11.56125119')),)
#a[0] is a tuple, use "*" to unpack a tuple when passing it as parameters:
In [11]: "Count: {}, Result: {}".format(*a[0])
Out[11]: 'Count: 79321, Result: 11.56125119'

see how to unpack argument lists, and format examples

or use the old %-formatting operator:

In [13]: "Count: %s, Result: %s"%a[0]
Out[13]: 'Count: 79321, Result: 11.56125119'
Community
  • 1
  • 1
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
2

If you're only expecting a single row as a result, then just use .fetchone() instead and then you don't have to worry unpacking it, eg:

print('Count: {} Result: {}'.format(*cur.fetchone()))

Or, if you have more, then loop over the cursor:

for row in cur:
    print('Count: {} Result: {}'.format(*row))
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
1

Another option, for varitey:

value = ((79321L, Decimal('11.56125119')),)
a, b = list(value)[0]
mmattax
  • 27,172
  • 41
  • 116
  • 149