Alireza Afzal Aghaei
Alireza Afzal Aghaei

Reputation: 1235

Combine python f-string with format

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

Answers (3)

filaton
filaton

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

Chris
Chris

Reputation: 22993

You need to put the 3 in curly braces as well:

>>> a = 2
>>> print(f"{a * 3}")
6
>>>

Upvotes: 6

Deepak Singh
Deepak Singh

Reputation: 411

You can try this.

print((int(f"{{a}}".format(a=2)))*3)

Upvotes: 0

Related Questions