[Tutor] % formatting
Scott Widney
SWidney@ci.las-vegas.nv.us
Wed Jan 15 19:34:01 2003
> It can be done without using eval(), as well --
>
> >>> def HH(level, text):
> ... text = text % level
> ... return "<H%d>%s</H%d>" % (level, text, level)
> ...
> >>> HH(3, 'This is level %d')
> '<H3>This is level 3</H3>'
> >>> HH(6, 'This is level %d')
> '<H6>This is level 6</H6>'
> >>>
>
> As has been mentioned in another thread, there are very few
> circumstances in which eval() is the only (or even best) way to do
> things. :) However, I think that this is *not* a good function
> design, in either form (yours or mine), because in either case, it
> requires the user of the function to know too much about the
> implementation details of the function -- i.e., what special
> characters ('%d' or '%(level)d') to include in the text string
> in order to get the proper substitution.
> I'd rather have the more explicit version that doesn't do
> additional formatting of the text string -- formatting the text
> should be separate from converting it to a marked-up html header.
I agree wholeheartedly; it was just a curiousity / mental exercise thing.
One thing I did not know was that % formatting worked outside the context of
the 'print' statement. I think the C language partition in my head is biting
me here; I've been thinking of 'print' as analogous to 'printf()'. Then
(correct me if I'm wrong here): 'print' is not a function and '%' is, what,
an overloaded operator ?
Scott