Does Python do variable interpolation similar to “string #{var}” in Ruby?

后端 未结 9 1186
盖世英雄少女心
盖世英雄少女心 2020-12-08 06:37

In Python, it is tedious to write:

print \"foo is\" + bar + \'.\'

Can I do something like this in Python?

print \"foo is #{ba

9条回答
  •  醉话见心
    2020-12-08 07:33

    I have learned the following technique from Python Essential Reference:

    >>> bar = "baz"
    >>> print "foo is {bar}.".format(**vars())
    foo is baz.
    

    This is quite useful when we want to refer to many variables in the formatting string:

    • We don't have to repeat all variables in the argument list again: compare it to the explicit keyword argument-based approaches (such as "{x}{y}".format(x=x, y=y) and "%(x)%(y)" % {"x": x, "y": y}).
    • We don't have to check one by one if the order of variables in the argument list is consistent with their order in the formatting string: compare it to the positional argument-based approaches (such as "{}{}".format(x, y), "{0}{1}".format(x, y) and "%s%s" % (x, y)).

提交回复
热议问题