Live data from Hacker News

Python f-strings are the best syntax sugar i never knew about

news.ycombinator.com

11–14 of 14 posts

Re: Python f-strings are the best syntax sugar i never knew about

#11

You can do cool nested calls with them too. >>> class A: ... def __init__(self): ... self.foo = 5 ... def bar(self): ... return 'cake' ... >>> a = A() >>> f'{a.foo}' '5' >>> f'{a.bar()}' 'cake' >>> x = {'b': 1, 'c': 2} >>> f"{x['b']}" '1'

saw this after posting, so epicly useful. Alreadying thinking of some nice concise, explanatory custom Exception descriptions..

Re: Python f-strings are the best syntax sugar i never knew about

#12
post #3

Ah yes, the thing we had in shell, Perl, and Ruby since forever, and that was never a very good idea.

Why wasn't it a good idea in these languages?

Because it's often hard to edit (which includes quoting or decoding where computation or variable starts) and because it mixes formatting and presenting data with computation.

Re: Python f-strings are the best syntax sugar i never knew about

#13
post #5

it is very very true. F-strings are awesome. But there is one use case that I prefer .format(), and is when formatting a string using a dictionary. Being able to is awesome: some_long_string_template.format(**some_dictionary_with_many_keys) For me that is such a nice and practical use case. But yes for not many local variables, f-string is the way to go.

I've only recently started learning Python, and the f-strings remind me a bit of the syntactic sugar provided by C# for string.Format() (var str = $"Hello, my name is {name}."; // for those who care)

I get the same feeling as well, and it's something I noticed a lot when it was a new feature to C#. Suddenly, everyone abandoned string.Format() in favour of $"", even when the code would lose a lot of readability.

Syntactic sugar is good and all, but I find it better to be more verbose for the sake of clarity.

Post reply on HN