Hacker News new | ask | show | jobs
by rement 1955 days ago
I have never seen f-strings! It's my lucky day! https://xkcd.com/1053/

Time to refactor the project I am currently working on that is loaded with `str.format()`

4 comments

Take a look at flynt, a tool that can convert older string formatting code to the newer fstring style. I've found it very helpful!

https://github.com/ikamensh/flynt

Can confirm. I replaced 1.5k instances in our code base in seconds using flynt and it knew the ones that couldn't be swapped out directly. Really great tool. You only ever need it once in your life, but that one time it's amazing.
Having not written Python in a long time until recently, I discovered fstrings. Are they the best choice for (nearly all) string formatting at least in new code? They seem to work pretty similarly to eg Ruby’s string interpolation.
Be aware that the only time this won't work is if you need to re-render the f-string with different context. For example you can do this:

    s = "this is {}"
    print(s.format("possible"))
but you cannot do that with f-strings because they are resolved on definition, so you could do something like this:

    for message in messages:
        print(f"The message is {message}")
But not this:

    s = f"The message is {message}"
    for message in messages:
        print(s)
This is the same drawback of JavaScript's Template Literals [0].

EDIT: Fix syntax in examples.

[0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...

f-strings are truly amazing. They're very painless. The only gotcha I've run into is accessing a dict from inside one. You need to watch out for your quotations :).
My most recent project makes liberal use of `f"""..."""`
Have you seen this? :)

    x, y = 1, 2
    print(f'{x=}, {y=}')
I haven't but that is awesome. That is a much better syntax than just outputting data with `print(x, y)` and remembering which came first (when debugging of course).