【问题标题】:python3 formatting SQL response from rows to stringpython3将SQL响应从行格式化为字符串
【发布时间】:2023-04-06 06:10:01
【问题描述】:

我试图从数据库中打印值并得到这个输出:

[('CPDK0NHYX9JUSZUYASRVFNOMKH',), ('CPDK0KUEQULOAYXHSGUEZQGNFK',), ('CPDK0MOBWIG0T5Z76BUVXU5Y5N',), ('CPDK0FZE3LDHXEJRREMR0QZ0MH',)]

但希望得到这个 fromat:

'CPDK0NHYX9JUSZUYASRVFNOMKH'|'CPDK0KUEQULOAYXHSGUEZQGNFK'|'CPDK0MOBWIG0T5Z76BUVXU5Y5N'|'CPDK0FZE3LDHXEJRREMR0QZ0MH'

Python3

现有代码

from coinpayments import CoinPaymentsAPI
from datetime import datetime
from lib.connect import *
import argparse
import json

sql = 'SELECT txn_id FROM coinpayment_transactions WHERE status = 0 '

mycursor.execute(sql)

result = mycursor.fetchall()

mydb.close()

print(result)

【问题讨论】:

  • 你至少需要展示你用来获取当前输出的代码。
  • "|".join(["'{}'".format(x[0]) for x in data] 假设您的数据是从数据库中读取的元组列表。

标签: python-3.x printing


【解决方案1】:

你得到的是一个元组列表,它存储在结果对象中。如果您希望按照您所说的方式格式化输出,请执行此操作

#Paste this instead of print(result)
output=''

for i in result:
    if (output!=''):
        output=output+'|'+"'"+i[0]+"'"
    else:
        output=output+"'"+i[0]+"'"
print(output)

做这些事情的更好方法是使用字符串的joinformat() 方法。

【讨论】:

  • 得到这个错误:output=output+"'"+i[0]+"'" NameError: name 'output' is not defined
  • @rimalonfire 我还有一个问题,你能帮忙聊聊还是我应该在这里添加?
  • 我从字符串中得到的“价值”是我们之前所说的
【解决方案2】:

这是您的解决方案:

output = '|'.join([f"'{row[0]}'" for row in result])
print(output)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 2019-06-03
    • 2014-10-15
    • 2010-10-07
    相关资源
    最近更新 更多