-3

i have this code:

cur.execute("SELECT numbers FROM table")
supp = cur.fetchall()
for item in supp:
    print item

and it prints:

('one',)
('two',)
('three',)

how can i have?

one
two
three
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218

2 Answers2

1

Each item correspond to a row of a result of your query, each row is represented by a tuple. If you want to get the first items of every tuple, you can unpack them in the for loop:

for value, in supp:
    print(value)

Or, you can just get the first items by index as well:

for row in supp:
    print(row[0])

You can also put them into a list with a list comprehension:

values = [value for value, in supp]

Demo:

>>> supp = [('one',), ('two', ), ('three', )]
>>> for value, in supp:
...     print(value)
... 
one
two
three
>>> [value for value, in supp]
['one', 'two', 'three']
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 1
    You can also used [namedtuple](https://docs.python.org/2.7/library/collections.html#collections.namedtuple)s to get more readable results from SQL queries. There's more information on using them [here](http://stackoverflow.com/a/20096972/6469907) and [here](http://stackoverflow.com/a/16336132/6469907). – pat Jul 07 '16 at 13:32
  • it's not a normal list... your example doesn't work as you think .-. – Aldin Selimbasic Jul 07 '16 at 13:35
  • @AldinSelimbasic well, let's start with what "does not work" for you? Any symptoms, errors? – alecxe Jul 07 '16 at 13:38
  • it returns elements as "('one',)" instead of "one" as i need – Aldin Selimbasic Jul 07 '16 at 13:40
  • 1
    @AldinSelimbasic sorry, may be there is some misunderstanding. Have you actually tried what I've posted? Thanks. – alecxe Jul 07 '16 at 13:41
  • dude, i have a PostgreSQL named "table", one of the columns is "numbers". By using a cursor i "capture" all values on the column numbers and put them inside a list. on my DB i have [ one, two, three ] as varchars but my list made of the "captured" elements isn't made by strings [ one, two, three ] but strings [ ('one',),('two',),('three',) ] i am looking for the method to have the well formatted strings returned – Aldin Selimbasic Jul 07 '16 at 13:46
  • btw, thnx for loosing time for me :/ – Aldin Selimbasic Jul 07 '16 at 13:47
  • This answer is an exact fit for you question. If you can't read it then @alecxe really squandered his time. – Clodoaldo Neto Jul 07 '16 at 14:27
0
try:
    supp = cur.fetchall()
    for item in supp:
        print ' | '.join(item)
    return "values printed"
except:
    return "Something went wrong!"
Ryan M
  • 18,333
  • 31
  • 67
  • 74