45

In Python, it is tedious to write:

print "foo is" + bar + '.'

Can I do something like this in Python?

print "foo is #{bar}."

dreftymac
  • 29,742
  • 25
  • 114
  • 177
mko
  • 20,242
  • 46
  • 127
  • 187
  • possible duplicate of [Format numbers to strings in Python](http://stackoverflow.com/questions/22617/format-numbers-to-strings-in-python) – Andreas Jung Aug 03 '12 at 02:36
  • I think I've found a solution, would you check it out? http://stackoverflow.com/questions/16504732/how-could-i-make-my-python-string-interpolation-implementation-work-accross-impo – HarmonicaMuse May 12 '13 at 10:25
  • Possible duplicate of [Is there a Python equivalent to Ruby's string interpolation?](https://stackoverflow.com/questions/4450592/is-there-a-python-equivalent-to-rubys-string-interpolation) – josemigallas Jun 15 '17 at 08:46

9 Answers9

62

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})
smci
  • 29,564
  • 18
  • 109
  • 144
Sean Vieira
  • 148,604
  • 32
  • 306
  • 290
28

Python 3.6 will have has literal string interpolation using f-strings:

print(f"foo is {bar}.")
AXO
  • 6,987
  • 4
  • 53
  • 56
11

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
>>> 
warvariuc
  • 53,721
  • 35
  • 166
  • 222
8

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:

  • We don't have to repeat all variables in the argument list again: compare it to the explicit keyword argument-based approaches (such as "{x}{y}".format(x=x, y=y) and "%(x)%(y)" % {"x": x, "y": y}).
  • We don't have to check one by one if the order of variables in the argument list is consistent with their order in the formatting string: compare it to the positional argument-based approaches (such as "{}{}".format(x, y), "{0}{1}".format(x, y) and "%s%s" % (x, y)).
dkim
  • 3,770
  • 1
  • 30
  • 35
  • 2
    That's an... odd way to pass in bar... Pretty neat though, makes it more closely follow the Ruby way. – Josiah Aug 03 '12 at 02:48
  • This seems like the best solution if you're working with an object. For example, if you are reporting an urllib2.HTTPError you can do `"HTTP error: {error.code} {error.msg}".format(**vars())` This doesn't work with `format(**locals())` – Mike T Oct 03 '14 at 08:27
5

String formatting

>>> bar = 1
>>> print "foo is {}.".format(bar)
foo is 1.
Josiah
  • 3,106
  • 21
  • 22
2

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())
Chris Johnson
  • 19,032
  • 5
  • 75
  • 76
  • But i guess it's very slow - unpacking a possibly big dict for the params. – warvariuc Aug 03 '12 at 05:36
  • @warwaruk writing to std out is the limiting factor, printing a string takes 10 times longer than formatting it, furthermore locals() returns a reference so I think this method is pretty fast – jcr Mar 21 '14 at 07:55
2

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

John La Rooy
  • 281,034
  • 50
  • 354
  • 495
0

Yes, absolutely. Python, in my opinion, has great support for string formatting, replacements and operators.

This might be helpful:
http://docs.python.org/library/stdtypes.html#string-formatting-operations

Slater Victoroff
  • 20,556
  • 18
  • 82
  • 140
Edmon
  • 4,594
  • 3
  • 29
  • 40
-1

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',))
valk
  • 8,655
  • 11
  • 54
  • 76