[Python-ideas] One way to do format and print

Andrew Barnert abarnert at yahoo.com
Mon Sep 7 22:47:59 CEST 2015


On Sep 7, 2015, at 09:48, Sven R. Kunze <srkunze at mail.de> wrote:
> 
>> On 07.09.2015 10:23, Chris Angelico wrote:
>> Which would you deprecate?
> 
> Hard to tell. Let me see what you got me here. Remember, I am just asking as I don't know better:
> 
>>      print("Hello, I am ", b, ". My favorite number is ", a, ".", sep="")
>> 
>> The print function stringifies all its arguments and outputs them,
>> joined by a separator. Aside from the 2/3 compatibility requirement
>> for single-argument print calls, there's no particular reason to
>> deprecate this. In any case, this isn't "yet another way to format
>> strings", it's a feature of print.
> 
> Still necessary?

Necessary? No. Useful? Yes.

For example, in a 5-line script I wrote last night, I've got print(head, *names, sep='\t'). I could have used print('\t'.join(chain([head], names)) instead--in fact, any use of multi-argument print can be replaced by print(sep.join(map(str, args)))--but that's less convenient, less readable, and less likely to occur to novices. And there are plenty of other alternatives, from print('{}\t{}'.format(head, '\t'.join(names)) to print(('%s\t'*(len(names)+1) % ((head,)+names))[:-1]) to that favorite of novices on Stack Overflow, print(str([head]+names)[1:-1].replace(', ', '\t')), but would you really want to use any of these?

Or course in a "real program" that I needed to use more than once, I would have used the csv module  instead of a 5-line script driven by a 3-line shell script, and there's a limit to how far you want to push the argument for quick&dirty scripting/interactive convenience... but that limit isn't "none at all".

When you start trying to mix manual adding of spaces with sep='' to get a sentence formatted exactly right, that's a good sign that you should be using format instead of multi-arg print; when you start trying to add up format strings, that's a good sign you should be using either something simpler or something more complicated. That is an extra thing novices have to get the hang of to become proficient Python programmers that doesn't exist for C or Perl. But the fact that you _can_ use Python like C, but don't have to, isn't really a downside of Python.


More information about the Python-ideas mailing list