Academic Work Personal
|
Python /
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 formattingmyDict = {'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 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 localsA 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.
It means that in the pattern you can use the name of the variables and they will be replaced by their values. |
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 Places Debrecen | France | Hungary | Montreal | Nancy Notes Hobby Projects * Jabba's Codes Quick Links [ edit ] |