Converting a List into Comma Separated and Add Quotes in Python

How to convert comma separated string enclosed in quotes, with spaces to a list with separate elements

Why don't you try something like this?

import re

String_tobe_Tested = " 'hello', 'Ruper's', 'how am i and', 'are','you'"
String_tobe_Tested = String_tobe_Tested.lstrip(' ')
String_tobe_Tested = String_tobe_Tested[1:-1]
print(String_tobe_Tested)
String_tobe_Tested = String_tobe_Tested.strip('"')
#String_tobe_Tested = eval(String_tobe_Tested)
#String_tobe_Tested = String_tobe_Tested.split("','")
String_tobe_Tested = re.compile("','|', '").split(String_tobe_Tested)
print(String_tobe_Tested)
print(len(String_tobe_Tested))

Join a list of strings such that each string is within quotes and comma separated

Do not use this for SQL query generation. Use the database driver SQL parameters instead. You cannot hope to properly escape your way out of SQL injection attacks otherwise.

If you need to use a WHERE .. IN .. test, generate placeholders:

query = 'SELECT * FROM table WHERE column IN ({})'.format(','.join(['%s'] * len(lst)))
cursor.execute(query, lst)

For everything else, use a list comprehension to add the quotes to the values, then join the results with commas:

', '.join(['"{}"'.format(value) for value in lst])

Demo:

>>> lst = ['John','Jack','Martin']
>>> ', '.join(['"{}"'.format(value) for value in lst])
'"John", "Jack", "Martin"'
>>> print ', '.join(['"{}"'.format(value) for value in lst])
"John", "Jack", "Martin"

This will consistently use " double quotes; simply use "'{}'" as the template if you must have single quotes instead.

join string by comma and put quotes around each element

In a single line using the split and join methods with a list comprehension.

s = 'abcd,efgh,igkl,mnop,qrst,uvwx,yz'

print(', '.join([f'"{w}"' for w in s.split(',')]))
# '"abcd", "efgh", "igkl", "mnop", "qrst", "uvwx", "yz"'


Related Topics



Leave a reply



Submit