15 points · by pyedpiper · 8y ago · 13 comments
>>> 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'It's much nicer to write this:
f"{account_name} {pretty_date(start_date)} - {pretty_date(end_date)} account attribution"
and MUCH easier to maintain than the alternative...!
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 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.
When you just want to interpolate a string on the fly, Fstrings are absolutely the right thing to do most of the time.