问题
I would like to go from this list:
my_list = [u'a','b','c',1,2,3]
...to this string, which maintains the quotes (for creating a sql statement):
my_string = "'a', 'b', 'c', 1, 2, 3"
This method works, but it sure is ugly!
my_string = str(my_list).replace('[','').replace(']','').replace('u','')
Is there a nicer way? What's wrong with heaping up the replaces - that can't be right!?
回答1:
disclaimer: you should NOT be preparing SQL using plain string manipulation! use a library appropriate for the database you are using to prepare statements.
for your edification (note this doesn't properly format unicode literals, you can feel free to replace repr
with a function with a special case for unicode):
my_string = ', '.join(repr(x) for x in my_list)
来源:https://stackoverflow.com/questions/25953959/turn-a-mixed-list-into-a-string-keep-quotes-only-for-strings