-1

Today stumbled upon Literal String Interpolation,

a=4
b=5
f'{a+b}'

the above code gives the output 9, I was trying to put the operation in variable too.

a=4
b='+'
c=5

Now how can Literal String Interpolation generate the expected output, saw the documentation but could not make much out of it.

someone
  • 104
  • 2
  • 10
  • Hi, many thanks for the downvote, kindly let me know what was it downvoted for or it was just for testing whether down vote works or not :p – someone Dec 17 '17 at 10:00

1 Answers1

1

You can use eval():

r = eval(f'{a}{b}{c}')

However, use of eval() is usually not recommended, since it will evaluate any string you feed to it. That includes arbitrary code a malicious user might have put in there somehow.

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
  • 1
    You don't need the `+`, `eval(f"{a}{b}{c}")` will work. – cdarke Dec 16 '17 at 08:39
  • @stybl, yup did see another post on stackoverflow that eval is evil, https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string – someone Dec 17 '17 at 09:59