Reputation: 1235
I want to calculate math operation in a f-string using a variable passed to format
method. For example i need something like :
print(f"{{a}} * 3".format(a=2))
This code prints:
2 * 3
But i want the result that's 6. Also i wont use python eval
function to evaluate this string.
Upvotes: 5
Views: 6863
Reputation: 2326
As stated by PEP 498:
The
str.format()
"expression parser" is not suitable for use when implementing f-strings.
While you could do something like:
name = "John"
age = 30
print(f'My name is {{0}} and I am 5 years older than {age - 5}'.format(name))
what you asked for in your original question is not doable.
You can also read this Reddit thread to see why that would probably be a bad idea.
Upvotes: 13
Reputation: 22993
You need to put the 3
in curly braces as well:
>>> a = 2
>>> print(f"{a * 3}")
6
>>>
Upvotes: 6