Python: How to Add Single Quotes to a Long List

Python add quotes to all elements in list?

native_american = {key: value[0].split(',') for key, value in native_american.items()}

What you have at the moment is a list of one long string. This splits it into a list of many smaller strings

Add quotes to every list element

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.

change single quotes to double quotes in list of dictionaries

Please use json.dumps like this:

import json

list1=[{'Name':'Jack','email':'xyz@foo.com'},
{'Name':'Sam','email':'sam@xyz.com'},
{'Name':'Dan','email':'dan@xyz.com'}]

print(list1)

list2 = json.dumps(list1)
print(list2)

#[{'Name': 'Jack', 'email': 'xyz@foo.com'}, {'Name': 'Sam', 'email': 'sam@xyz.com'}, {'Name': 'Dan', 'email': 'dan@xyz.com'}]
#[{"Name": "Jack", "email": "xyz@foo.com"}, {"Name": "Sam", "email": "sam@xyz.com"}, {"Name": "Dan", "email": "dan@xyz.com"}]

How to put list values with single quotes as well as double quotes to Postgressql Select Query

Do not use format to construct the query. Simply use %s and pass the tuple into execute

query = """select category from  "unique_shelf" where "Unique_Shelf_Names" in %s """

cur.execute(query,(list2,))

Tuples adaptation

Adding single quotes to a value of a variable

Add the double quotation marks around it: '"' + foo + '"'. Or f'"{foo}"', if you prefer format strings.



Related Topics



Leave a reply



Submit