[Python-ideas] One way to do format and print
Sven R. Kunze
srkunze at mail.de
Mon Sep 7 18:48:15 CEST 2015
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?
> print("Hello, I am " + b + ". My favorite number is " + str(a) + ".")
>
> String concatenation is definitely not going away; but even without
> PEP 498, I would prefer to use percent formatting or .format() above
> this. Its main advantage over those is that the expressions are in the
> right place, which PEP 498 also offers; if it lands, I fully expect
> 3.6+ code to use it rather than this. But the _functionality_ can't be
> taken away.
For sure, however that shouldn't be used in the official documentation
if so now, right?
> print("Hello, I am {}. My favorite number is {}.".format(b, a))
>
> This one is important for non-literals. It's one of the two main ways
> of formatting strings...
>
> print("Hello, I am %s. My favorite number is %s." % (b, a))
>
> ... and this is the other. Being available for non-literals means they
> can be used with i18n, string tables, and other transformations.
> Percent formatting is similar to what other C-derived languages have,
Still necessary? Really, really necessary? Or just because we can?
> and .format() has certain flexibilities, so neither is likely to be
> deprecated any time soon.
format has its own merits as it works like f-strings but on
non-literals. (again this one-way/one-syntax thing)
> print("Hello, I am {b}. My favorite number is {a}.".format_map(locals()))
>
> This one, though, is a bad idea for several reasons. Using locals()
> for formatting is restricted - no globals, no expressions, and no
> nonlocals that aren't captured in some other way. If this one, and
> this one alone, can be replaced by f-string usage, it's done its job.
Well sure, I we all agree on not using that until f-strings are released.
Best,
Sven
More information about the Python-ideas
mailing list