Page 1 of 1
Trying to understand f-strings...
Posted: Wed Nov 10, 2021 6:41 pm
by pythoncoder
This works with
string.format, with the caller being able to define the format of a value computed at run time:
Code: Select all
def bar(s="{}"):
v = 4.2
print(s.format(v))
Is there a way to do this with f-strings? This fails on the first line because v is undefined.
Code: Select all
def foo(s=f"{v}"):
v = 4.2
print(s)
It seems that the f-string is compiled, with its value, when it is declared. So this delivers 99:
Code: Select all
v = 99
def foo(s=f"{v}"):
v = 4.2
print(s)
So is there a way to declare an f-string which formats a value which changes at run time?
Re: Trying to understand f-strings...
Posted: Wed Nov 10, 2021 8:58 pm
by jim
Would this work for your needs?
Code: Select all
def foo(s=None):
v = 4.2
if s is None:
s = f"{v}"
print(s)
Re: Trying to understand f-strings...
Posted: Wed Nov 10, 2021 10:45 pm
by bulletmark
Formatted string literals (i.e. f-strings) are not intended to replace str.format() in every case. When you have a string with embedded replacement fields which you need to replace later in time, then just call .format() on it at that time. No point trying to use an f-string here.
Re: Trying to understand f-strings...
Posted: Wed Nov 17, 2021 10:06 am
by joshfreeman
I am having issues to understanding this.
Re: Trying to understand f-strings...
Posted: Wed Nov 17, 2021 6:31 pm
by jim
Re: Trying to understand f-strings...
Posted: Thu Nov 18, 2021 7:44 am
by pythoncoder
I think @bulletmark is right in this instance and string format must be used. Looking at your function:
Code: Select all
def foo(s=None):
v = 4.2
if s is None:
s = f"{v}"
print(s)
my typical call pattern would be:
This fails with
NameError: name 'v' isn't defined.