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

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


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})


Python 3.6 has introduced f-strings:

print(f"foo is {bar}.")

Old answer:

Since version 3.2 Python has str.format_map which together with locals() or globals() allows you to do fast:

Python 3.3.2+ (default, Feb 28 2014, 00:52:16) >>> bar = "something">>> print("foo is {bar}".format_map(locals()))foo is something>>>