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

后端 未结 9 1188
盖世英雄少女心
盖世英雄少女心 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:32

    There is a big difference between this in Ruby:

    print "foo is #{bar}."
    

    And these in Python:

    print "foo is {bar}".format(bar=bar)
    

    In the Ruby example, bar is evaluated
    In the Python example, bar is just a key to the dictionary

    In the case that you are just using variables the behave more or less the same, but in general, converting Ruby to Python isn't quite so simple

提交回复
热议问题