Python Forum
reading an f-string from a file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
reading an f-string from a file
#1
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
You could perhaps eval('f' + repr(bar)) (untested, I'm with 3.5 and I don't like f-strings)
Reply
#3
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#4
I don't know if fstrings support
 f'it is now {__import__("time").time()} seconds past epoch'
Reply
#5
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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  reading a file like the unix tail -f command does Skaperen 1 57 4 hours ago
Last Post: perfringo
  reading and writing a image stored in a file Skaperen 4 2,171 Feb-12-2022, 04:03 AM
Last Post: Skaperen
  reading remote active log file? korenron 3 2,816 Jun-24-2021, 09:07 AM
Last Post: korenron

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020