[Tutor] String formatting

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Sat Aug 20 18:39:42 CEST 2005


Kent Johnson a écrit :
> Pierre Barbier de Reuille wrote:
> 
[...]
> 
> 
>>Well, when using the "%" operator on string always put a tuple or a
>>dictionnary on the RHS :
>>
>>print "Connection from %s" % (info,)
> 
> 
> No, you can put a single item on the right without putting it in a tuple:
>  >>> print 'x = %s' % 3
> x = 3
> 

I never said it does not work, but I say it is Bad Practice (TM). The
reason (as I already explained) is, if the variable suddently happen to
become a tuple the semantic of your print statement will change !

Just try that if you're not convinced :

>>> def foo(x):
...   print "x = %s" % x

>>> foo(3)

>>> foo((3,))

>>> foo((1,2,3))

Now, if you change the function with :

>>> def foo(x):
...   print "x = %s" % (x,)

It will always work as intended ! And when you're debugging this is
*very* important !

Pierre

-- 
Pierre Barbier de Reuille

INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP
Botanique et Bio-informatique de l'Architecture des Plantes
TA40/PSII, Boulevard de la Lironde
34398 MONTPELLIER CEDEX 5, France

tel   : (33) 4 67 61 65 77    fax   : (33) 4 67 61 56 68


More information about the Tutor mailing list