How to remove extra comma in cur.fetchall()
Question:
I tried to output all values in a column in mysql however, it also outputs extra comma in the end.
def numbers():
db = getDB();
cur = db.cursor()
sql = "SELECT mobile_number FROM names"
cur.execute(sql)
result = cur.fetchall()
for x in result:
print(x)
It looks like this in shell:
(0123456789,)
(9876543210,)
Answers:
a couple more options:
# validate that the results contain exactly one column
for [x] in result:
print(x)
and
# using argument unpacking
for x in result:
print(*x)
Basically as Ben’s comment says the comma doesn’t technically exist, it is there because it is a tuple.
but is you still want to remove it try this:
rows=[i[0] for i in rows]
I tried to output all values in a column in mysql however, it also outputs extra comma in the end.
def numbers():
db = getDB();
cur = db.cursor()
sql = "SELECT mobile_number FROM names"
cur.execute(sql)
result = cur.fetchall()
for x in result:
print(x)
It looks like this in shell:
(0123456789,)
(9876543210,)
a couple more options:
# validate that the results contain exactly one column
for [x] in result:
print(x)
and
# using argument unpacking
for x in result:
print(*x)
Basically as Ben’s comment says the comma doesn’t technically exist, it is there because it is a tuple.
but is you still want to remove it try this:
rows=[i[0] for i in rows]