将元组列表打印为字符串

Print a list of tuples as a string

我有一个元组列表

[
 ('User: ', '<@268326653795500044>, ', 1), 
 ('User: ', '<@381118832963616779>, ', 3), 
 ('User: ', '<@510489897790996492>, ', 1)
]

这就是我创建元组列表的方式

curs.execute('SELECT userID, strike FROM user WHERE strike != 0')
records = curs.fetchall()

rows = []

for row in records:
  string = 'User: ', f'<@{row[0]}>, ', row[1]
  rows.append(string)
print(rows)

我想打印成字符串: 字符串:用户:<@268326653795500044>, 1

尝试

string_list = []
for x,y,z in records:
   str = x+':'+y+','+str(z)
   string_list.append(str)

编辑:避免 Sushant 在评论中提到的索引

它只是一个元组列表,因为这是您使用 , 而不是 + 进行连接创建的:

curs.execute('SELECT userID, strike FROM user WHERE strike != 0')
records = curs.fetchall()
    
rows = []
    
for row in records:
   string = 'User: ' +  f'<@{row[0]}>, ' + row[1] # now we have a string instead of a tuple
   rows.append(string)
    
print(rows)

正如一条评论指出您使用的是 f 字符串,那么为什么不一路走下去呢:

string = f'User: <@{row[0]}>, {row[1]}' # now we have a 
data = [('User: ', '<@268326653795500044>, ', 1), 
('User: ','<@381118832963616779>, ', 3), 
('User: ', '<@510489897790996492>, ', 1)]


for i in data:
    print(f"{' '.join(map(str,i))}")

您可以像评论指出的那样使用 .join()。您的元组中确实有整数,因此必须将它们转换为字符串,然后才能与元组中的其他字符串值连接。

输出:

User:  <@268326653795500044>,  1
User:  <@381118832963616779>,  3
User:  <@510489897790996492>,  1