Reputation: 173
From my database, I'm returning a list to be displayed into my HTML page but my list has this unwanted symbols. I tried using split()
function but it wont work. How can I remove those parenthesis,commas and quotes. Thanks for you help
The output is :
[('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]
I want:
[cenomar, cedula, Birth Certificate, Clearance]
Here is my python function:
@app.route('/')
def search():
conn=psycopg2.connect("dbname='forms' user='postgres' password='everboy'
host='localhost' port='5432'")
cur=conn.cursor()
cur.execute("SELECT name from form")
rows=cur.fetchall()
print(rows)
return render_template("form.html",rows=rows)
Upvotes: 4
Views: 5778
Reputation: 11
Try this one
l = [('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]
b = []
for i in l:
b.append(i[0])
print(b)
Upvotes: 0
Reputation: 1823
An easy solution would be:
Input: ["('cenomar',)", "('cedula',)", "('Birth Certificate',)", "('Clearance',)"]
rows = ["('cenomar',)", "('cedula',)", "('Birth Certificate',)", "('Clearance',)"]
res = []
for r in rows:
res.append(r[2:-3]) # this line ignores the beginning bracket and open quote and the closing bracket, comma, and close quote
print res
Output: ["cenomar", "cedula", "Birth Certificate", "Clearance"]
What happens is, you iterate over your list, and for each item you just cut off the things you don't need with the use of string manipulation ([n:m]
, where n
is the starting character and m
is the end character, in your case 2
indicates to start the string from the 3 character (ignoring the (
and '
) and -3
indicates cut the string to 3 characters before the end of it (ignoring the )
, '
, and ,
)).
EDIT 1
I noticed that your input may not be a string as my above answer suggests, if you have a tuple ("smth",)
you can just simply get the 1st element. So the answer would change to:
Input: [('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]
rows = [('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]
res = []
for r in rows:
res.append(r[0])
print res
Output: ["cenomar", "cedula", "Birth Certificate", "Clearance"]
The above implementation is written in long for ease of understanding, but as well can be translated into a shorter one liner like so:
rows = [i[0] for i in rows]
Hope this helps!
Upvotes: 1
Reputation: 910
After This line: rows=cur.fetchall()
add this line
rows=[i[0] for i in rows]
Upvotes: 13