2

I'm trying to retrieve some data stored in a mysql table and the output has some additional commas which I don't need.

>>> cursor.execute("SELECT REMOTE_INT FROM R3")
2L
>>> x = cursor.fetchall()
>>> x
((u'xe-0/0/0',), (u'xe-0/0/1',))
>>> x[0]
(u'xe-0/0/0',)
>>> x[1]
(u'xe-0/0/1',)
>>>

Also any suggestions on removing the 'u'? I want to be able to use these values of x in other parts of the script.

2
  • The commas are not 'extra commas' - they're indications that the object you're getting back is a tuple (or tuple of tuples in this case) and your result is the first item in the tuple. The u indicates the data is a unicode string; it won't stop you from using the data anywhere else in the code. Commented Mar 8, 2017 at 5:47
  • 1
    Thanks for the feedback. I understand its a tuple but i wasnt sure how to use the value in my script because of the additional commas. But i think i have the answer now. Commented Mar 8, 2017 at 7:18

1 Answer 1

6

As per the fetchall documentation.

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.

I am not a big fan of fetchall and would like to suggest that you use fetchone or use the cursor as an iterator. however all of these methods still return a tuple.

You can convert the tuple returned to you into a simple list by doing

[ x[0] for x in cursor.fetchall()]

This effectively 'removes the extra comma'

Sign up to request clarification or add additional context in comments.

1 Comment

Done! Thanks for the tip!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.