pythonstring-formattingstring-interpolation

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


In Python, it is tedious to write:

print "foo is" + bar + '.'

Can I do something like this in Python?

print "foo is #{bar}."


Solution

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