使用列表元素中的Python格式化字符串

时间:2013-06-25 15:56:35

标签: python python-2.7

我有一个包含两个元素的列表:

tr = ['table1', 'table2']

我希望能够生成查询的一部分并获取此信息:

table1 INNER JOIN table2 ON table1.id = table2.id

我怎么能用Python做到这一点?

任何帮助都将不胜感激。

编辑: 以下是我尝试制作table1 INNER JOIN table2

的内容
join_tables = ('%s LEFT JOIN %s'.format(' '.join('%s' for _ in range(element -1))) for element in tr)

1 个答案:

答案 0 :(得分:3)

"{0} INNER JOIN {1} ON {0}.id = {1}.id".format("table1", "table2")

修改

如果这是一个合法的例子,你需要使用cursor.execute("{0} INNER JOIN {1} ON {0}.id = {1}.id", ("table1", "table2"))用于MySQL,或cursor.mogrify(...)用于Postgres以正确地转义表名并防止SQL注入。