【问题标题】:Using arrays with python's string.format()将数组与 python 的 string.format() 一起使用
【发布时间】:2015-01-21 03:21:51
【问题描述】:

我如何以如下方式使用string.format()

line = 'first {0}, second {1}'
print(line.format([1,2]))

将打印first 1 second 2

【问题讨论】:

  • 请注意,仅在 Python 2.6 中才需要对格式字段进行显式编号。所有现代版本的 Python 都会为你做这件事,所以你只需要:line = 'first {}, second {}'

标签: python arrays string list format


【解决方案1】:

你可以unpack the list:

>>> line = 'first {0}, second {1}'
>>> l = [1, 2]
>>> print(line.format(*l))
first 1, second 2

【讨论】:

  • 通常最好避免命名变量l,以避免混淆Il1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 2011-02-11
  • 2018-08-17
  • 2017-03-19
  • 2015-10-05
  • 1970-01-01
  • 2023-04-06
相关资源
最近更新 更多