Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable interpolation in Python [duplicate]

Tags:

python

string

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

like image 475
Aillyn Avatar asked Aug 22 '10 18:08

Aillyn


2 Answers

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' }
like image 148
knutin Avatar answered Oct 21 '22 03:10

knutin


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.

like image 41
Sam Dolan Avatar answered Oct 21 '22 02:10

Sam Dolan