String formatting in Python

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

    Since python-3.6, Python supports literal string interpolation [pep-498]. You thus can format with an f prefix to the string. For example:

    x = 1
    y = 2
    z = 3
    f'[{x}, {y}, {z}]'

    This then produces:

    >>> f'[{x}, {y}, {z}]'
    '[1, 2, 3]'
    

    In C# (the language of the String.Format(…)) in the question, since c#-6.0, string interpolation [microsof-tdoc] is supported as well, for example:

    int x = 1;
    int y = 2;
    int z = 3;
    string result = $"[{x}, {y}, {z}]";

    For example:

    csharp> int x = 1;
    csharp> int y = 2;
    csharp> int z = 3;
    csharp> $"[{x}, {y}, {z}]";
    "[1, 2, 3]"
    

提交回复
热议问题