[Tutor] string formatting (%s)

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



On Sat, 15 Apr 2006, Tiago Saboga wrote:

> Can I use string formatting in my own functions, or is it stuck with builtins?
> It doesn't make much sense for me, but I don't understand the following
> error:
>
> In [1]: var = 456
>
> In [2]: def printd(arg):
>   ...:     print('>>> %s') % arg
>   ...:

Hi Tiago,

Ah!  printd() is not doing what you think it's doing.  Try:

#########################
def printd(arg):
     print ('>>> %s' % arg)
#########################

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.


More information about the Tutor mailing list