将混合列表转换为字符串,仅对字符串使用引号 [英] turn a mixed list into a string, keep quotes only for strings
本文介绍了将混合列表转换为字符串,仅对字符串使用引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从此列表中删除:
my_list = [u'a','b','c',1,2,3]
...到此字符串,该字符串保留引号(用于创建sql语句):
...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','')
有更好的方法吗?
推荐答案
免责声明:您不应该使用纯字符串操作来准备SQL!使用适合您用于准备语句的数据库的库.
为您的教育(请注意,这不能正确格式化unicode文字,您可以随意将repr
替换为具有unicode特殊情况的函数):
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)
这篇关于将混合列表转换为字符串,仅对字符串使用引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文