【问题标题】:Output python query output into string将python查询输出输出为字符串
【发布时间】:2019-08-15 20:40:22
【问题描述】:

尝试使用这种语法:

import MySQLdb as mdb
con = mdb.connect(host = 'host', user = 'user', passwd = 'pwd', db = 'db');
cur = con.cursor()
cur.execute('select distinct name from names');
rows = cur.fetchall()
print(rows)
(('1',), ('2',), ('3',), ('4',), ('5',))

我需要将此输出设为字符串格式,以便我可以将其作为变量包含在另一个查询中,我将在同一脚本中运行。

'1','2','3','4','5'

我从命令行运行它并尝试了一些事情:

>>> for row in rows:
...   print "%s," % row
...

但不幸的是没有给我我需要的东西。

【问题讨论】:

    标签: mysql-python gae-python27


    【解决方案1】:
    rows = ('1',), ('2',), ('3',), ('4',), ('5',)
    output1=output2=""
    
    for row in rows:
        output1 += '\'' + str(row[0][0]) + '\'' + ','
        output2 += ' ' + str(row[0][0]) + ' ' + ','
    
    # To delete last char: ','
    output1 = output1[:-1]
    output2 = output2[:-1]
    
    print(rows)          # (('1',), ('2',), ('3',), ('4',), ('5',))
    print(output1)       # '1','2','3','4','5'
    print(output2)       #  1 , 2 , 3 , 4 , 5 
    

    output1 是您所期望的,但您可能应该将 output2 字符串提供给您的脚本。

    【讨论】:

    • 谢谢!像魅力一样工作。
    猜你喜欢
    • 1970-01-01
    • 2017-11-30
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    相关资源
    最近更新 更多