String formatting in Python

后端 未结 12 2117
-上瘾入骨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:38

    You have lot of solutions :)

    simple way (C-style):

    print("[%i, %i, %i]" %(1, 2, 3))
    

    Use str.format()

    print("[{0}, {1}, {2}]", 1, 2, 3)
    

    Use str.Template()

    s = Template('[$a, $b, $c]')
    print(s.substitute(a = 1, b = 2, c = 3))
    

    You can read PEP 3101 -- Advanced String Formatting

提交回复
热议问题