[Tutor] String formatting
Kent Johnson
kent37 at tds.net
Sun Aug 21 03:05:07 CEST 2005
Ah, thanks for the explanation. I've never been tripped up by that...
Kent
Pierre Barbier de Reuille wrote:
> 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
>
More information about the Tutor
mailing list