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

mko picture mko · Aug 3, 2012 · Viewed 30.5k times · Source

In Python, it is tedious to write:

print "foo is" + bar + '.'

Can I do something like this in Python?

print "foo is #{bar}."

Answer

Sean Vieira picture Sean Vieira · Aug 3, 2012

Python 3.6+ does have variable interpolation - prepend an f to your string:

f"foo is {bar}"

For versions of Python below this (Python 2 - 3.5) you can use str.format to pass in variables:

# Rather than this:
print("foo is #{bar}")

# You would do this:
print("foo is {}".format(bar))

# Or this:
print("foo is {bar}".format(bar=bar))

# Or this:
print("foo is %s" % (bar, ))

# Or even this:
print("foo is %(bar)s" % {"bar": bar})