Remix.run Logo
throwaway2037 8 days ago

I promise, no trolling from me in this comment. I never understood the advantage of Python f-strings over printf-style format strings. I tried to Google for pros and cons and didn't find anything very satisfying. Can someone provide a brief list of pros and cons? To be clear, I can always do what I need to do with both, but I don't know f-strings nearly as well as printf-style, because of my experience with C programming.

Mawr 8 days ago | parent | next [-]

Sure, here are the two Go/C-style formatting options:

    fmt.Sprintf("This house is %s tall", measurements(2.5))

    fmt.Sprint("This house is ", measurements(2.5), " tall")
And the Python f-string equivalent:

    f"This house is {measurements(2.5)} tall"
The Sprintf version sucks because for every formatting argument, like "%s", we need to stop reading the string and look for the corresponding argument to the function. Not so bad for one argument but gets linearly worse.

Sprint is better in that regard, we can read from left to right without interruptions, but is a pain to write due to all the punctuation, nevermind refactor. For example, try adding a new variable between "This" and "house". With the f-string you just type {var} before "house" and you're done. With Sprint, you're now juggling quotation marks and commas. And that's just a simple addition of a new variable. Moving variables or substrings around is even worse.

Summing up, f-strings are substantially more ergonomic to use and since string formatting is so commonly done, this adds up quickly.

throwaway2037 8 days ago | parent [-]

    > Not so bad for one argument but gets linearly worse.
This is a powerful "pro". Thanks.
theptip 8 days ago | parent | prev [-]

    _log(f”My variable is {x + y}”)
Reads to me a lot more fluently to me than

    _log(“My variable is {}”.format(x+y)) 
or

    _log(“My variable is {z}”.format(z=x+y))
It’s nothing too profound.
blami 6 days ago | parent [-]

I am not very familiar with Python. How do you localize (translate) first one?

wzdd 4 days ago | parent [-]

You don't with f-strings because they're substituted eagerly. You could with the new t-strings proposed here because you can get at the individual parts.