48

In Python, it is tedious to write:

print "foo is" + bar + '.'

Can I do something like this in Python?

print "foo is #{bar}."

dreftymac
  • 31,404
  • 26
  • 119
  • 182
mko
  • 21,334
  • 49
  • 130
  • 191
  • 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

10 Answers10

66

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
  • 32,567
  • 20
  • 113
  • 146
Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • 1
    The 3rd one looks neat, but I remember this way kinda deprecated? is that true? – mko Aug 03 '12 at 02:52
  • 10
    There is also, for the lazy, `print "foo is %(bar)s" % locals()`. – Brian M. Hunt Aug 03 '12 at 02:58
  • 1
    @yozloy - correct it is deprecated in Python 3 (as I understand it). – Sean Vieira Aug 03 '12 at 02:58
  • @SeanVieira what's the over taker of this solution? – mko Aug 03 '12 at 03:14
  • Strange the fact that Python has something explicit. –  Jul 07 '15 at 18:39
  • 1
    the % syntax is no longer deprecated in Python 3: http://stackoverflow.com/a/23381153/770425 – Jeff Widman Dec 18 '15 at 01:48
  • What does "it is explicit rather than implicit" imply in this context? `print "foo is #{bar}."`, for example, looks very explicit to me – Lem Ko Dec 13 '16 at 05:40
  • The quote-as-operator-context is what's implicit (to my mind) - `print "foo is #{bar}"` vs. `print 'foo is #{bar}'` is implicit compared to `"foo is {bar}".format(bar=bar)` or even Python 3.6's `f"foo is {bar}"` – Sean Vieira Dec 16 '16 at 06:50
  • 1
    This is incorrect since [3.6 introduced f-strings](https://docs.python.org/3.7/reference/lexical_analysis.html#index-20) – smci Sep 07 '18 at 01:01
28

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

print(f"foo is {bar}.")
AXO
  • 8,198
  • 6
  • 62
  • 63
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
  • 57,116
  • 41
  • 173
  • 227
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,930
  • 1
  • 33
  • 37
  • 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,266
  • 24
  • 24
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
  • 20,650
  • 6
  • 81
  • 80
  • 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
  • 295,403
  • 53
  • 369
  • 502
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
  • 21,376
  • 21
  • 85
  • 144
Edmon
  • 4,752
  • 4
  • 32
  • 42
0

You can also use Template Strings like this:

from string import Template
s = Template('$who likes $what')
s.substitute(who='tim', what='kung pao')
# 'tim likes kung pao'

This works really well for when you want to build the string template ahead of time and inject the variable elsewhere

See Also: PEP 292 – Simpler String Substitutions

KyleMit
  • 30,350
  • 66
  • 462
  • 664
-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
  • 9,363
  • 12
  • 59
  • 79