In Python, it is tedious to write:
print \"foo is\" + bar + \'.\'
Can I do something like this in Python?
print \"foo is #{ba
I prefer this approach because you don't have to repeat yourself by referencing the variable twice:
alpha = 123 print 'The answer is {alpha}'.format(**locals())
Almost every other answer didn't work for me. Probably it's because I'm on Python3.5. The only thing which worked is:
print("Foobar is %s%s" %('Foo','bar',))
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 will have has literal string interpolation using f-strings:
print(f"foo is {bar}.")
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
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:
"{x}{y}".format(x=x, y=y)
and "%(x)%(y)" % {"x": x, "y": y}
)."{}{}".format(x, y)
, "{0}{1}".format(x, y)
and "%s%s" % (x, y)
).