Does Python do variable interpolation similar to “string #var” in Ruby?

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."


print "foo is #bar."






possible duplicate of Format numbers to strings in Python

– Andreas Jung
Aug 3 '12 at 2:36






I think I've found a solution, would you check it out? stackoverflow.com/questions/16504732/…

– SalchiPapa
May 12 '13 at 10:25







Possible duplicate of Is there a Python equivalent to Ruby's string interpolation?

– josemigallas
Jun 15 '17 at 8:46




9 Answers
9



Python 3.6+ does have variable interpolation - prepend an f to your string:


f


f"foo is bar"



For versions of Python below this (Python 2 - 3.5) you can use str.format to pass in variables:


str.format


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






The 3rd one looks neat, but I remember this way kinda deprecated? is that true?

– mko
Aug 3 '12 at 2:52






There is also, for the lazy, print "foo is %(bar)s" % locals().

– Brian M. Hunt
Aug 3 '12 at 2:58


print "foo is %(bar)s" % locals()






@yozloy - correct it is deprecated in Python 3 (as I understand it).

– Sean Vieira
Aug 3 '12 at 2:58






the % syntax is no longer deprecated in Python 3: stackoverflow.com/a/23381153/770425

– Jeff Widman
Dec 18 '15 at 1:48






@smci - good point. Updated!

– Sean Vieira
Sep 8 '18 at 0:32



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


print(f"foo is bar.")






In case anyone was wondering: yes, you can combine this with say raw strings, like so rf"foo is bar".

– Toni Sučić
Feb 20 '17 at 7:40


rf"foo is 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:


str.format_map


locals()


globals()


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



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:


"xy".format(x=x, y=y)


"%(x)%(y)" % "x": x, "y": y


"".format(x, y)


"01".format(x, y)


"%s%s" % (x, y)






That's an... odd way to pass in bar... Pretty neat though, makes it more closely follow the Ruby way.

– Josiah
Aug 3 '12 at 2: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 3 '14 at 8:27



"HTTP error: error.code error.msg".format(**vars())


format(**locals())



String formatting


>>> bar = 1
>>> print "foo is .".format(bar)
foo is 1.






or older but still popular: print "foo is %s" % str(bar)

– Edmon
Aug 3 '12 at 2:39






That's supposed to be deprecated by now, though I can't find the PEP.

– Josiah
Aug 3 '12 at 2:41






Not deprecated, just superseded.

– Sean Vieira
Aug 3 '12 at 2:42






I guess in Python 2 it's not, but it was at least supposed to be deprecated by 3.1, which was released some time ago.

– Josiah
Aug 3 '12 at 2:45




I prefer this approach because you don't have to repeat yourself by referencing the variable twice:






But i guess it's very slow - unpacking a possibly big dict for the params.

– warvariuc
Aug 3 '12 at 5: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 7:55



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


bar


bar



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






This is incorrect since 3.6. We now have print(f"foo is #bar")

– smci
Sep 7 '18 at 1:00


print(f"foo is #bar")



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



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',))



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)