Add quotes to every list element

后端 未结 4 2000
自闭症患者
自闭症患者 2020-12-13 09:10

I\'m very new to python. I need a simple and clear script to add quotes to every list elements. Let me explain more. Here is the my code.

parameters = [\'a\'         


        
4条回答
  •  庸人自扰
    2020-12-13 09:31

    A naive solution would be to iterate over your parameters list and append quotes to the beginning and end of each element:

    (', '.join('"' + item + '"' for item in parameters))
    

    Note: this is vulnerable to SQL injection (whether coincidental or deliberate). A better solution is to let the database quote and insert these values:

    query = "SELECT * FROM foo WHERE bar IN (%s)" % ','.join('?' * len(params))
    cursor.execute(query, params)
    

    It's easier to read and handles quoting properly.

提交回复
热议问题