i am reading a string from a file. how can i have it be interpreted as an f-string?
num = 123456789
with open('thefile') as openf: # this file has: number is {num}
bar = do_f_string(openf.readline().rstrip())
foo = f'number is {num}'
print(foo)
print(bar)
the above code should output the same line twice when
do_f_string()
is the function doing what i seek.
You could perhaps eval('f' + repr(bar))
(untested, I'm with 3.5 and I don't like f-strings)
it seems to work in eval(). something else i wanted to do in an f-string is have it evaluated at use so f'it is now {time.time()} seconds past epoch'
reports the time when the string is used, not when it is created. eval() can do that, though it would have been nice to have a special kind of object that works just like a string but evaluates its own contents at time of use. that would also mean i can create f'it is now {time.time()} seconds past epoch'
before time is defined or imported.
I don't know if fstrings support
f'it is now {__import__("time").time()} seconds past epoch'
i tried that on my 3.6.8 and the result was an ordinary string. i think that's a limitation of f-strings. they are just a different way to express the definition of a string. it won't even let me make a byte string that way. once it's done, you have just a string and nothing more is done (without special code like eval()). i still find it useful where the expression is at the point of use.