简体   繁体   中英

Python list | How to remove parenthesis,quotes and commas in my list?

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)

在此行之后: rows=cur.fetchall()添加此行

rows=[i[0] for i in rows]

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!

Try this one

l = [('cenomar',), ('cedula',), ('Birth Certificate',), ('Clearance',)]
b = []
for i in l:
    b.append(i[0])
print(b)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM