Printing variables in python with placeholders

No matter what kind of programming background you come from, when you stumble upon python it’s hard to deny how easy the code just seems to flow from the fingertips.

steelcase-inigomontoya

Even if you’ve only dabbled with python for a minute or two, you’ve probably already figured out that you can print variables using placeholders, like this:

#!/usr/bin/env python
f = 'Inigo'
l = ''Montoya'
print "Hello. My name is %s %s. You killed my father. Prepare to die." % f, l

steelcase-mrgrinch

You might have tried concatenation too, but be careful – bad things happen when you add strings and integers. It’s best to avoid this method completely, but for reference:

#!/usr/bin/env python
fname = 'The'
lname = 'Grinch'
n = 0
print "I'm " + fname + lname + " and there'll be " + n + " more Christmas's!"

steelcase-ironman
However, did you know you can print using %s but with the variable names directly?

#!/usr/bin/env python
first = 'Iron'
last = 'Man'
print "The truth is... I am %(first)s %(last)s." % globals()
Posted by admica   @   6 May 2011

Related Posts

0 Comments

No comments yet. Be the first to leave a comment !
Leave a Comment

Name

Email

Website

*

Previous Post
«
Next Post
»
Powered by Wordpress   |   Lunated designed by ZenVerse

Valid XHTML 1.0 Transitional