3 ms·
I have never seen f-strings! It's my lucky day! https://xkcd.com/1053/ https://xkcd.com/1053/ Time to refactor the project I am currently working on that is lo
by rement 6y ago
I have never seen f-strings! It's my lucky day! https://xkcd.com/1053/ https://xkcd.com/1053/
Time to refactor the project I am currently working on that is loaded with `str.format()`
- ZephyrBlu 6y agof-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 :).
- mumblemumble 6y agoMy most recent project makes liberal use of `f"""..."""`
- ilovetux 6y agoBe 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/Reference/Template_literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- matt_trentini 6y agoTake 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 https://github.com/ikamensh/flynt
- aidos 6y agoCan 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.
- andrewem 6y agoHaving 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.
- pythonslayer 6y agoYes. I’m not sure about speed, but syntactically they are far superior and better for all cases, unless of course you’re wanting to pass templates as an input, but that’s pretty obvious.
- aldanor 6y agoHave you seen this? :) x, y = 1, 2 print(f'{x=}, {y=}')
- rement 6y agoI 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).