String formatting in Python

后端 未结 12 2009
-上瘾入骨i
-上瘾入骨i 2020-11-22 08:14

I want to do something like String.Format(\"[{0}, {1}, {2}]\", 1, 2, 3) which returns:

[1, 2, 3]

How do I do this in Python?

12条回答
  •  抹茶落季
    2020-11-22 08:57

    The previous answers have used % formatting, which is being phased out in Python 3.0+. Assuming you're using Python 2.6+, a more future-proof formatting system is described here:

    http://docs.python.org/library/string.html#formatstrings

    Although there are more advanced features as well, the simplest form ends up looking very close to what you wrote:

    >>> "[{0}, {1}, {2}]".format(1, 2, 3)
    [1, 2, 3]
    

提交回复
热议问题