【问题标题】:How to apply list to string.format() parameters? [duplicate]如何将列表应用于 string.format() 参数? [复制]
【发布时间】:2015-02-20 16:37:34
【问题描述】:

Python 2.x CSV 输入示例(我有很多)

67.60.60.24, 1384, application/octet-stream,18/Feb/2015:00:00:50

期望的输出:

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。请改用 SQL 参数。
  • 哦...是的!谢谢!

标签: python list string-formatting


【解决方案1】:

您可以使用 * 运算符解包列表。

你的情况

sql = sqlTemplate.format(*list)

如果你的列表是["a", "b", "c"],这段代码是一样的:

sql = sqlTemplate.format("a", "b", "c")

当然,你现在可以用不同数量的参数调用格式化函数

【讨论】:

    猜你喜欢
    • 2018-03-12
    • 1970-01-01
    • 2023-02-07
    • 2018-12-19
    • 1970-01-01
    • 2013-12-14
    • 2021-04-25
    • 2017-06-28
    • 1970-01-01
    相关资源
    最近更新 更多