【问题标题】:How do I print a value without any brackets or commas or parenthesis?如何打印没有任何括号或逗号或括号的值?
【发布时间】:2022-11-12 23:25:54
【问题描述】:

我只想打印没有任何括号、逗号或括号的值。我正在将 MySQL 与带有 mysql.connector 的 python 一起使用。

当我运行此代码时,我得到“('esrvgf',)”。但我只想得到“esrvg”。

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="password",
  database ="mydatabase"
)

cursor = mydb.cursor()


sql = "select nick from users where ipaddress = '192.168.1.4'"

cursor.execute(sql)

myresult = cursor.fetchall()

for x in myresult:
  print(x)

【问题讨论】:

  • 听起来你正在得到一个元组。试试print(*x)print(x[0])

标签: python mysql mysql-python mysql-connector


【解决方案1】:

cursor.fetchall() 返回一个元组列表(参见this question)。您需要做的就是用x[0] 打印第一个元素。像这样:

for x in myresult:
  print(x[0])

或者,您可以使用* 运算符将元组的每个元素作为参数传递给print()。像这样:

for x in myresult:
  print(*x)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多