[Tutor] string formatting (%s)

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Apr 16 07:53:46 CEST 2006


> The parenthesization you had earlier forced Python into printing out 
> your template before it had an opportunity to plug arg into it.  You 
> need to do the interpolation first.

Gaaah.  Brain freeze.

I was pointing at the wrong code.  *grin*


I meant to look at the other statement that you had, the one that raised 
the error:

##############################
var = 456
def printd(arg):
     print(">>> %s") % arg
printd(var)
printd('Variable is %s') % var
##############################

There might be two possibilities to fix this code.  One will do the 
interpolation first:


##############################
var = 456
def printd(arg):
     print(">>> %s") % arg
printd(var)
printd('Variable is %s' % var)
##############################


But the other possible fix is to change printd() from being a side-effect 
function to something that actually returns something:

###################################
var = 456
def arrow(arg):
     return (">>> %s" % arg)
print arrow(var)
print arrow('Variable is %s') % var
###################################

This second approach is better: functions that return values are more 
reusable than ones that are fixated on printing things to the screen.


More information about the Tutor mailing list