3 ms·
F-string are great and should have been in the language since the beginning. Many other languages had with their own version of them since version 0. What I don
by pmontra 7y ago
F-string are great and should have been in the language since the beginning. Many other languages had with their own version of them since version 0. What I don't understand is why Python needs a special string type when other languages can interpolate normal strings (Ruby, Elixir, JavaScript.)
- duckerude 7y agof-strings need a prefix so old strings can keep working the same way. If `print("{x}")` printed "{x}" in Python 3.5, it shouldn't print something else in a newer version. But `print(f"{x}")` was a syntax error before f-strings, so no code is broken by giving it a meaning. JavaScript can't interpolate ordinary strings either, for the same reason. You need to use backticks (``).
- pmontra 7y agoYou're correct about JavaScript. I forgot about the backticks. Thank you for the explanation of the f-strings. I'm pretty sure that migrating old strings to "\{x\}" could be automated but we can't force everybody to migrate their code. There is probably no other way than the one they followed.
- Dylan16807 7y agoIt's also just safer. You want your default string type to have as few gotchas about what can be put in it as possible.
- duckerude 7y ago"\{x\}" includes the backslashes into the string literally. So even if that worked for f-strings it would change the meaning for older Python versions. Requiring people to update common old code is also just something to avoid unless necessary. The correct way to escape braces in f-strings is with double braces, so f"{{x}}". This is consistent with the way str.format works. f-string syntax is very similar to str.format syntax in general.
- mixmastamyk 7y agoShells do it with "" and ''. Unfortunately Py and Js decided to allow both for regular strings, so there is not such an easy way to delineate them.
- sametmax 7y agoBecause explicit is better than implicit.