

Join the discussion
Write your take first — we'll ask for email only when you're ready to publish.
- Hacker News
- Great new way to write blog posts!by madprops
- Been using python for almost 10 years. I never use any of the funky strings.
Instead of reading like 10 PEPs for f strings, I just use the + operator on strings and backslash escaping, big whoop.
by TZubiri - Right, because x + " " + y is more clear than of simply f"{x} {y}".
Been using python for longer than 10 years and immediately started using f-strings when I could. It takes almost no time to understand the basics.
by smohare - age = 32
print(f"Age: {age}")
Thus concludes the lecture on f-strings.
by andai - Instead of 10 PEPs, you could read one helpful cheatsheet: https://www.pythonmorsels.com/string-formatting/#cheat-sheet....by PyWoody
- Not really about the content of the blog post but am I the only one bothered by the complete lack of capitalization? Granted it may be because of my screen reader but my TTS engine of choice doesn't pause on un-capitalized words/sentences/phrases/etc. which follow a full stop, so this post unless I read it line by line (minus the code) just blends into complete noise.by ethin
- Whenever I'm building a JSON document, I revert to the old %s syntax just because it's more tidy than an f-string.by smitty1e
- Am I understanding that you’re building JSON with string interpolation? If so any special reason you wouldn’t build a dict and json.dumps() it?by folkrav
- do not get the funny part of the pythons string.by cocodill
- here's a valid f-string:
>>> f'{'}'}' '}'
Huh? I remember learning the rule that you can't nest quotes inside fstrings if they are the same kind (unlike in bash) - e.g
would be a syntax error, butf"{mydict["foo"]}"
orf"{mydict['foo']}"
would be valid.f'{mydict["foo"]}'The reason being the same like for the rstring weirdness: The lexer comes first and identifies the string literal, then for fstrings, the python parser is invoked again for each {...} expression to parse it.
This is unlike other nested expressions, which are already split up by the lexer and then parsed in one go.
Did that change at some point?
by xg15 - Update: They really changed it! (in python 3.12)
There was a PEP about it:
https://stackoverflow.com/questions/78388333/nested-quotes-i...
https://docs.python.org/3.12/whatsnew/3.12.html#pep-701-synt...
by xg15 - I think this is pretty intuitive (I was able to answer the question correctly before opening the spoiler), but I really like raw string designs in Rust and C++11 that allow you to stop worrying about escaping completely.by vova_hn2
- In his 2017 PyCon Israel keynote, "The Fun of Reinvention", Dave Beazley made a wonderfully mischievous case for taking advantage of new Python features instead of making every new project carry the accumulated baggage of old Python versions.
Talking about Python 3.6, he said it was "probably one of the most major Python releases that has ever been made." His demonstration intentionally used new features that made the code incompatible with older interpreters. This was a prototype, so why not use the interesting new tools?
He was especially enthusiastic about f-strings: "F-strings are just awesome."
I was originally skeptical about them, but he convinced me to reconsider. One implementation detail that later helped win me over was that CPython 3.6 added dedicated FORMAT_VALUE and BUILD_STRING opcodes for f-strings. That does not mean an f-string is faster than simply doing a + b when both values are already strings -- simple concatenation usually wins that particular race -- but f-strings are generally cleaner, and often faster than older formatting machinery such as str.format().
I agree with his argument. There are vanishingly few situations in which a new project genuinely must support ancient Python releases. If your employer refuses to let you use a reasonably current version without a concrete technical reason, that is a warning sign. Life is too short to program indefinitely for obsolete interpreters.
The keynote:
https://www.youtube.com/watch?v=js_0wjzuMfc
Beazley's other talks:
by DonHopkins - Goofy edge cases aside, I think f-strings are great.by phyzome
- I'm not a fan of f-strings.
I feel like 90% of new Python features in the last 10 years just increased language complexity without any benefit.
by dwdz - It doesn’t have to be beneficial, it just has to be “pythonic.”by odyssey7
- Indeed, and I get that one can ignore those features (I do), but finding them in existing code or having the AI coding agent use them diminishes the "easy for beginners" aspect.by analog31
- It is baffling to me that Python seems to insist on reinventing language features and coming up with the most incomprehensible of designs. The whole dataclass and serialisation ecosystem comes to mind, as well as the evolution of typing.
The language exposes so much of its internals that even if the design were consistent, the ecosystem of (buggy) libs and tools makes it inconsistent.
by ajrouvoet - I like f-strings but I don't like that there are at least five ways to format stings.
1. %-formatting [1]
2. str.format [2]
3. string.Template [3]
4. f-string [4]
5. t-string [5]
What happened to "one-- and preferably only one --obvious way to do it"? [6]
Also, the way string formatting interacts with logging is a total mess. People just pass f-strings to logging, which seems to be an intuitive way to do it. Except it limits your options if you want to collect structured logs and it doesn't allow you to use late evaluation based on log level.
[1] https://docs.python.org/3/library/string.html#format-example...
[2] https://docs.python.org/3/library/stdtypes.html#str.format
[3] https://docs.python.org/3/library/string.html#string.Templat...
[4] https://docs.python.org/3/reference/lexical_analysis.html#f-...
[5] https://docs.python.org/3/reference/lexical_analysis.html#t-...
by vova_hn2 - I'm a HUGE fan of f-strings and I think they should be added to more or less every language in existence. (This is just to show how much I like f-strings, not to be taken literally) `printf`-style format strings seem outdated: why use format strings when I can put my variables IN THE STRING? I want the result of `x+y` to be put {HERE} in this string. Well, just write `"This is here: {x+y} blah"` — it makes perfect sense and immediately lets me see what the resulting strings generally look like.
Basic usage is a no-brainer: write your string, put variables or short expressions in curly braces, add `printf`-style format specifiers after the colon. This is also great because it's a natural extension of `printf`-style format strings.
Of course you can write complicated and confusing f-strings. But then you can write complicated and confusing... anything, really. Many programming languages have extremely weird quirks and cases where basic syntax can be transformed into an unreadable monstrosity, like C syntax for pointers to functions and arrays.
Sure, this increases the language's complexity, but you don't have to use all of it to reap the benefits.
by ForceBru - Whenever I read people's takes about Python on HN, I always feel like I'm using an entirely different language.by PyWoody
- I feel ya. I don’t write a lot of it anymore, but have written probably hundreds of thousands of lines over the years. It has a few rough edges, but over all it’s solid and I’ve used it to make lots things I’m proud of.by kstrauser
- That you know how to use the language without such oddities presenting any difficulty does not make them less strange. That r-string parsing solution is fine for the interpreter, but we are not interpreters, so it's not a logical outcome for Python authors,
The most puzzling thing is few languages use the absolute simplest solution to escaping quotes, which happens to be especially useful for non-expanded literals, and that's good ol' quote-doubling. Difficult for Python to introduce now since it'd be a bc-break for implied concatenation, but if space were required between them, we could have had
x = r'ex\x20cape!\'
y = 'diff''rent'
z = 'diff' 'erent'
respectively containing
ex\x20cape!\
diff'rent
different
TOML has a similar issue: it is impossible to store its delimiter for non-expanded multi-line strings inside a multi-line non-expanded string. There's no method to escape it. Whilst this is rarely an issue in practice, it's odd that there's unnecessary difficulty in writing about TOML inside a TOML document. Again, it could have used the simpler quote-doubling method for all strings (even easier because no concatenation), with similar rules for non-expanded and multi-line variants. Then there would be no limitation on what can be stored in any literal type. Instead it has a peculiarity that's illogical and offers no benefit to us authors.
by Walf