HOME - Recent Changes - Search:

Academic Work


Personal

* pot de départ


dblp


(:twitter:)

-----

[ edit | logout ]
[ help | sandbox | passwd ]

sprintf in Python

#############################

Migrated to http://pythonadventures.wordpress.com/2010/10/04/sprintf-in-python2/.

str = "pi is %.2f, name is %s" % (3.1415, "Boba")
print str   # pi is 3.14, name is Boba

The stuff after '%' is a tuple.


Dictionary-based string formatting

myDict = {'solo': 'Han Solo', 
          'jabba': 'Jabba the Hutt'}
print "%(solo)s was captured by %(jabba)s." % myDict   # Han Solo was captured by Jabba the Hutt.

Values are taken from the dictionary myDict. In the pattern you need to specify the keys in parentheses.

What is it good for? It's more readable because otherwise when you see "%s" you have to check on the right side what it is, then you jump back with your eyes, etc. Hey, this is not a table tennis match, right?


Dictionary-based string formatting with locals

A variation of the previous solution:

solo = 'Han Solo'
jabba = 'Jabba the Hutt'
print locals()   
# {'solo': 'Han Solo', '__builtins__': <module '__builtin__' (built-in)>, '__file__': './sprintf.py', 
#'__package__': None, 'jabba': 'Jabba the Hutt', '__name__': '__main__', '__doc__': None}
print "%(solo)s was captured by %(jabba)s." % locals()   # Han Solo was captured by Jabba the Hutt.

locals returns a copy of the local namespace as a dictionary where the keys are the variable names and the values are their respective values.

It means that in the pattern you can use the name of the variables and they will be replaced by their values.

Cloud City


anime | bash | blogs | bsd | c/c++ | c64 | calc | comics | convert | cube | del.icio.us | digg | east | eBooks | egeszseg | elite | firefox | flash | fun | games | gimp | google | groovy | hardware | hit&run | howto | java | javascript | knife | lang | latex | liferay | linux | lovecraft | magyar | maths | movies | music | p2p | perl | pdf | photoshop | php | pmwiki | prog | python | radio | recept | rts | scala | scene | sci-fi | scripting | security | shell | space | súlyos | telephone | torrente | translate | ubuntu | vim | wallpapers | webutils | wikis | windows


Blogs and Dev.

* Ubuntu Incident
* Python Adventures
* me @ GitHub


Places

Debrecen | France | Hungary | Montreal | Nancy


Notes

full circle | km


Hobby Projects

* Jabba's Codes
* PmWiki
* Firefox
* PHP
* JavaScript
* Scriptorium
* Tutorials
* me @ GitHub


Quick Links


[ edit ]

View - Edit - History - Attach - Print *** Report - Recent Changes - Search
Page last modified on 2010 October 05, 02:48