[Tutor] To FORMAT or not to

Alan Gauld alan.gauld at btinternet.com
Mon Jan 4 05:04:41 EST 2016


On 04/01/16 03:46, Steven D'Aprano wrote:

>>     fmtString = "You've visited {0} & {2}."
>>     if foo:
>>       print(fmtString.format(foo,bar))
>>     else:
>>       print(fmtString.format(baz,bad))
> 
> I wouldn't write it like that. I'd write:
> 
>     if foo:
>         args = (foo, bar)
>     else:
>         args = (baz, bad)
>     print("You've visited {} & {}.".format(*args))

In this case yes but the point I was trying to illustrate
was that you often want to print the same message from
several different places in your code - even in different
functions for example. Using a format string helps keep
that consistent. The if/else construct was just the most
concise example I could think of.

> but now we're out of the realm of simple uses like the Original Poster's 
> code. 

Indeed, and I did point that out at the start of my message.
Apart from one string addition the OPs use of print was
pretty seamless. But he wanted to know why the other
programmer thought formatting was better, not whether we thought
formatting was better in his particular case. At least that's
how I read it.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list