1

Im working with mysql.connection library to Python and I have this method:

query = ("select " + columns + " from " + table)
self.cursor.execute(query)
data = self.cursor.fetchall()
for row in data:
    print row

In my print row, I get something like this:

(u'Kabul', u'AFG', u'Kabol', 1780000)

I would like to get it as a string, this result:

Kabul AFG Kabol 1780000

I can do this:

print row[0] + ' ' + row[1] + row[2] + ' ' + row[3]

But it will not work if the user sets a query with less than 4 columns or more than 4.

I also was thinking about a loop in my tuple, but I get this result:

Kabul
AFG
Kabol
1780000

Some idea?

tsuda7
  • 413
  • 1
  • 6
  • 25
BigBugCreator
  • 1,009
  • 4
  • 17
  • 34

2 Answers2

4

You can use join but will run into errors when joining a list of mixed unicode and integers. Use the built in str function and list comprehension to create your intended output.

print ' '.join(str(x) for x in row)
dnix
  • 121
  • 4
2

If row is a tuple you could join every value in it using space:

print " ".join(row)
# Kabul AFG Kabol 1780000

So, it doesn't matter how many columns a user has selected, it will always join what row has.

UPDATE:

Above code works only if the values in row are string, so you need to first convert values to string and then join

print " ".join(map(str, row))
AKS
  • 18,983
  • 3
  • 43
  • 54