11

Possible Duplicate:
Unpythonic way of printing variables in Python?

In PHP one can write:

$fruit = 'Pear';
print("Hey, $fruit!");

But in Python it's:

fruit = 'Pear'
print("Hey, {0}!".format(fruit))

Is there a way for me to interpolate variables in strings instead? And if not, how is this more pythonic?

Bonus points for anyone who gets the reference

Community
  • 1
  • 1
Aillyn
  • 23,354
  • 24
  • 59
  • 84
  • 3
    All the existing answers are (severely) obsolete as of Python 3.x and in particular 3.6. With [f-strings in 3.6](https://docs.python.org/3.7/reference/lexical_analysis.html#index-20) we can now do `print(f'Hey, {fruit}!')` And much more (all the formatting operators, access list elements and attributes, call `str()` or `repr()` with `!s` or `!r` ... – smci Sep 07 '18 at 00:41

5 Answers5

12

The closest you can get to the PHP behaviour is and still maintaining your Python-zen is:

print "Hey", fruit, "!"

print will insert spaces at every comma.

The more common Python idiom is:

print "Hey %s!" % fruit

If you have tons of arguments and want to name them, you can use a dict:

print "Hey %(crowd)s! Would you like some %(fruit)s?" % { 'crowd': 'World', 'fruit': 'Pear' }
anon
  • 4,578
  • 3
  • 35
  • 54
knutin
  • 5,033
  • 19
  • 26
7

The way you're doing it now is a pythonic way to do it. You can also use the locals dictionary. Like so:

>>> fruit = 'Pear'
>>> print("Hey, {fruit}".format(**locals()))
Hey, Pear

Now that doesn't look very pythonic, but it's the only way to achieve the same affect you have in your PHP formatting. I'd just stick to the way you're doing it.

Sam Dolan
  • 31,966
  • 10
  • 88
  • 84
  • 2
    Yeah, you *can* - but while you're at it, how about switching to the "new" string formatting? `%`-formatting will be removed some day... –  Aug 22 '10 at 18:29
  • This looks even worse than the way I am doing it – Aillyn Aug 22 '10 at 18:33
  • 2
    It's extremely bad style to use `locals()`, never do this. Pass the actual values you want to put in the string instead. – Allen Feb 10 '12 at 21:04
  • @Allen: Yeah it is bad style.. I know that, but it's the only way to do what he wants in python. – Sam Dolan Feb 10 '12 at 23:35
2

A slight adaptation from the NamespaceFormatter example in PEP-3101:

import string

class NamespaceFormatter(string.Formatter):
  def __init__(self, namespace={}):
      super(NamespaceFormatter, self).__init__()
      self.namespace = namespace

  def get_value(self, key, args, kwds):
      if isinstance(key, str):
          try:
              # Check explicitly passed arguments first
              return kwds[key]
          except KeyError:
              return self.namespace[key]
      else:
          super(NamespaceFormatter, self).get_value(key, args, kwds)

fmt = NamespaceFormatter(globals())
fruit = 'Pear'

print fmt.format('Hey, {fruit}!')

for:

Hey, Pear!
Matt Anderson
  • 19,311
  • 11
  • 41
  • 57
1

Something like this should work:

"%(fruit)s" % locals()
kloffy
  • 2,928
  • 2
  • 25
  • 34
-3

Don't do it. It is unpythonic. As example, when you add translations to your app, you can't longer control which variables are used unless you check all the translations files yourself.

As example, if you change a local variable, you'll have to change it in all translated strings too.

leoluk
  • 12,561
  • 6
  • 44
  • 51