Python f-strings are the best syntax sugar i never knew about
1–10 of 14 posts
Re: Python f-strings are the best syntax sugar i never knew about
#2Re: Python f-strings are the best syntax sugar i never knew about
#3Re: Python f-strings are the best syntax sugar i never knew about
#4 >>> 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'Re: Python f-strings are the best syntax sugar i never knew about
#5 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.Re: Python f-strings are the best syntax sugar i never knew about
#6When you just want to interpolate a string on the fly, Fstrings are absolutely the right thing to do most of the time.
Re: Python f-strings are the best syntax sugar i never knew about
#7You 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'
Re: Python f-strings are the best syntax sugar i never knew about
#8You 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'
Interesting. Thanks for the post. I always just concatenated them out of laziness, and this looks even lazier.
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...!
Re: Python f-strings are the best syntax sugar i never knew about
#9Ah yes, the thing we had in shell, Perl, and Ruby since forever, and that was never a very good idea.
Re: Python f-strings are the best syntax sugar i never knew about
#10Templated strings are great for when, as the name suggests, you want to create a string with some placeholders to be expanded at a later time. When you just want to interpolate a string on the fly, Fstrings are absolutely the right thing to do most of the time.