[Tutor] Beginners question

Mats Wichmann mats at wichmann.us
Sat Apr 4 09:57:39 EDT 2020


On 4/3/20 5:19 PM, boB Stepp wrote:
> On Fri, Apr 3, 2020 at 6:35 AM Alan Gauld via Tutor <tutor at python.org> wrote:
> 
>> Perhaps the worst example in Python is string formatting.
>> We now have at least 4 different ways of formatting strings.
>> That's at least 2 too many...
> 
> Out of curiosity, which one(s) do you prefer to use and what shapes
> your preference(s)?

For me, as an old C programmer, the printf-style formatting style is
fine, I'm used to it - that's where Python's syntax came from.  If that
were the only style available, I'm pretty sure that would be holding
Python back, and that's almost certainly the reason other methods have
developed.

I sure wish they'd thought of f-strings before inventing the .format
method, that's the one we could do without - because it doesn't fix one
of the two big problems with string formatting, that of having to match
up the arguments with the format string.  How many of us get that wrong
over and over when there's a lengthy list of args?

msg = "error %d, file %s line %d" % (e, f, l)
msg = "error {}, file {} line {}".format(e, f, l)

wow, what a difference!! :(

I constantly find myself realizing I needed to print out one more value,
and then forget to add the corresponding entry to the tuple or format
args, and get a traceback...

But:

msg = f"error {e}, file {f}, line {l}"

and for quick debug prints (yeah, yeah, I know - don't debug with
prints, use proper logging):

print(f"error {e=}, file {f=}, line {l=}")

which shortcuts having to manually write the name of the variable
together with the the value, i.e. it is sugar for:

print(f"error e={e}, file f={f}, line l={l}")

which obviously matters more when you use proper identifier names that
are more than one character!

all the format-specificiers are possible, e.g. I can write the number 10
as a float with two digits on the rhs:

print(f"{10:.2f}")
10.00

and full expressions are possible within the braces {}

f-strings are definitely my preference - keeping what you're
interpolating into the string closely coupled with how you're doing so
just seems like a massive win in readability, maintainanbility, etc.





More information about the Tutor mailing list