原文: https://thepythonguru.com/python-string-formatting


    于 2020 年 1 月 7 日更新


    format()方法允许您以任何所需的方式格式化字符串。

    语法template.format(p1, p1, .... , k1=v1, k2=v2)

    模板是一个包含格式代码的字符串,format()方法使用它的参数替换每个格式代码的值。 例如:

    1. >>> 'Sam has {0} red balls and {1} yellow balls'.format(12, 31)

    {0}{1}是格式代码。 格式代码{0}替换为format()的第一个参数,即12,而{1}替换为format()的第二个参数,即31

    预期输出

    1. Sam has 12 red balls and 31 yellow balls

    对于简单的格式化,该技术是可以的,但是如果要在浮点数中指定精度怎么办? 对于这种情况,您需要了解有关格式代码的更多信息。 这是格式代码的完整语法。

    语法{[argument_index_or_keyword]:[width][.precision][type]}

    type可以与格式代码一起使用:

    格式码 描述
    d 用于整数
    f 用于浮点数
    b 用于二进制数
    o 八进制数
    x 八进制十六进制数
    s 用于字符串
    e 用于指数格式的浮点

    以下示例将使事情更加清楚。

    示例 1

    1. >>> "Floating point {0:.2f}".format(345.7916732)

    在这里,我们指定精度的2位,f用于表示浮点数。

    预期输出

    1. Floating point 345.79

    示例 2

    1. >>> import math
    2. >>> "Floating point {0:10.3f}".format(math.pi)

    在这里,我们指定3精度数字,10表示宽度,f表示浮点数。

    预期输出

    1. Floating point 3.142

    示例 3

    1. "Floating point pi = {0:.3f}, with {1:d} digit precision".format(math.pi, 3)

    这里{1:d}中的d表示整数值。

    预期输出

    1. Floating point pi = 3.142, with 3 digit precision

    如果为整数ValueError指定精度,则仅在浮点数的情况下才需要指定精度。

    示例 5

    1. 'Sam has {1:d} red balls and {0:d} yellow balls'.format(12, 31)

    预期输出

    1. Sam has 31 red balls and 12 yellow balls

    示例 6

    1. "In binary 4 is {0:b}".format(4) # b for binary, refer to Fig 1.1

    预期输出

    1. In binary 4 is 100

    示例 7

    1. array = [34, 66, 12]
    2. "A = {0}, B = {1}, C = {2}".format(*array)

    预期输出

    1. A = 34, B = 66, C = 12

    示例 8

    1. d = {
    2. 'hats' : 122,
    3. 'mats' : 42
    4. }
    5. "Sam had {hats} hats and {mats} mats".format(**d)

    预期输出

    1. Sam had 122 hats and 42 mats

    format()方法还支持关键字参数。

    1. 'Sam has {red} red balls and {green} yellow balls'.format(red = 12, green = 31)

    请注意,在使用关键字参数时,我们需要在{}内部使用参数,而不是数字索引。

    您还可以将位置参数与关键字参数混合

    1. 'Sam has {red} red balls, {green} yellow balls \
    2. and {0} bats'.format(3, red = 12, green = 31)

    格式化字符串的format()方法是一个非常新的方法,它是在 Python 2.6 中引入的。 您将在旧版代码中看到另一种古老的技术,它允许您使用%运算符而不是format()方法来格式化字符串。

    让我们举个例子。

    1. "%d pens cost = %.2f" % (12, 150.87612)

    在这里,我们使用%左侧的模板字符串。 我们使用%代替格式代码的{}。 在%的右侧,我们使用元组包含我们的值。 %d%.2f被称为格式说明符,它们以%开头,后跟代表数据类型的字符。 例如,%d格式说明符是整数的占位符,类似地%.2f是浮点数的占位符。

    因此,%d被替换为元组的第一值,即12,而%.2f被替换为第二值,即150.87612

    预期输出

    1. 12 pens cost = 150.88

    一些更多的例子。

    示例 1

    新:

    1. "{0:d} {1:d} ".format(12, 31)

    旧:

    1. "%d %d" % (12, 31)

    预期输出

    1. 12 31

    示例 2

    New:

    1. "{0:.2f} {1:.3f}".format(12.3152, 89.65431)

    Old:

    1. "%.2f %.3f" % (12.3152, 89.65431)

    预期输出

    1. 12.32 89.654

    示例 3

    New:

    1. "{0:s} {1:o} {2:.2f} {3:d}".format("Hello", 71, 45836.12589, 45 )

    Old:

    1. "%s %o %.2f %d" % ("Hello", 71, 45836.12589, 45 )

    预期输出

    1. Hello 107 45836.13 45