turn a mixed list into a string, keep quotes only for strings

拈花ヽ惹草 提交于 2019-12-24 02:24:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!