Python 如何将列表应用于string.format()参数?
Python2.x 示例CSV输入(我有很多) 期望输出:Python 如何将列表应用于string.format()参数?,python,list,string-formatting,Python,List,String Formatting,Python2.x 示例CSV输入(我有很多) 期望输出: insert into mytable (ip, bytes, type, timestamp) values ('67.60.60.24', 1384, 'application/octet-stream', '2015-02-18') 到目前为止: sqlTemplate = "insert into mytable (ip, bytes, type, timestamp) values ('{0}', {1}, '{2}', '
insert into mytable (ip, bytes, type, timestamp) values ('67.60.60.24', 1384, 'application/octet-stream', '2015-02-18')
到目前为止:
sqlTemplate = "insert into mytable (ip, bytes, type, timestamp) values ('{0}', {1}, '{2}', '{3}')
# lines contains many of the above sample input CSV lines
for line in lines:
list = line.split(",")
list = [elem.strip() for elem in list] # whitespace strip each element
# Make sure len(list) == 4
if len(list) != 4:
continue
sql = sqlTemplate.format(list) # how can i apply the list to the args?
# todo: insert sql into DB
您可以使用*运算符解压缩列表 就你而言
sql = sqlTemplate.format(*list)
如果您的列表为[“a”、“b”、“c”],则此代码与以下代码相同:
sql = sqlTemplate.format("a", "b", "c")
但是,当然,现在可以使用不同数量的参数调用format函数不要使用字符串格式来生成SQL。改用SQL参数。哦…是的!非常感谢。
sql = sqlTemplate.format("a", "b", "c")