Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/60.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将格式设置为cursor.fetchall()结果_Python_Mysql_Tuples - Fatal编程技术网

Python 将格式设置为cursor.fetchall()结果

Python 将格式设置为cursor.fetchall()结果,python,mysql,tuples,Python,Mysql,Tuples,我正在使用mysql.connection库连接到Python,我有以下方法: query = ("select " + columns + " from " + table) self.cursor.execute(query) data = self.cursor.fetchall() for row in data: print row 在我的打印行中,我得到如下内容: (u'Kabul', u'AFG', u'Kabol', 1780000) 我希望将其作为字符串获取,结果如

我正在使用mysql.connection库连接到Python,我有以下方法:

query = ("select " + columns + " from " + table)
self.cursor.execute(query)
data = self.cursor.fetchall()
for row in data:
    print row
在我的打印行中,我得到如下内容:

(u'Kabul', u'AFG', u'Kabol', 1780000)
我希望将其作为字符串获取,结果如下:

Kabul AFG Kabol 1780000
Kabul
AFG
Kabol
1780000
我可以这样做:

print row[0] + ' ' + row[1] + row[2] + ' ' + row[3]
但是,如果用户设置的查询的列数少于4列或多于4列,那么它将不起作用

我也在考虑元组中的循环,但我得到了这个结果:

Kabul AFG Kabol 1780000
Kabul
AFG
Kabol
1780000

一些想法?

如果
是一个
元组
,您可以使用空格连接其中的每个值:

print " ".join(row)
# Kabul AFG Kabol 1780000
因此,无论用户选择了多少列,它都会加入
中的内容

更新:

上述代码仅在行中的值为字符串时有效,因此需要首先将值转换为字符串,然后进行连接

print " ".join(map(str, row))

如果
元组
,则可以使用空格连接其中的每个值:

print " ".join(row)
# Kabul AFG Kabol 1780000
因此,无论用户选择了多少列,它都会加入
中的内容

更新:

上述代码仅在行中的值为字符串时有效,因此需要首先将值转换为字符串,然后进行连接

print " ".join(map(str, row))

您可以使用
连接
,但在连接unicode和整数混合列表时会出错。使用内置的
str
功能和列表理解创建您的预期输出

print ' '.join(str(x) for x in row)

您可以使用
连接
,但在连接unicode和整数混合列表时会出错。使用内置的
str
功能和列表理解创建您的预期输出

print ' '.join(str(x) for x in row)

如果元组中的任何内容不是字符串,则此操作将失败。谢谢。我更新了答案。如果元组中的任何内容不是字符串,则此操作将失败。谢谢。我更新了答案。这很好=)谢谢。我想补充一点,我得到了一个unicode错误或类似的错误,我用这个来解决:print“。join(str(unicode(c)。encode('utf-8'))for c in row)这很好=)谢谢。我想补充一点,我得到了一个unicode错误或类似的错误,我用这个来解决:print“。join(str(unicode(c).encode('utf-8'))表示行中的c)