svijay
svijay

Reputation: 23

How to remove extra commas when retrieving data from mysql using python

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.

Upvotes: 2

Views: 3988

Answers (1)

e4c5
e4c5

Reputation: 53734

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'

Upvotes: 6

Related Questions