5

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.

0

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah, nice find with that PEP 498 excerpt. I was looking for something like that to explain why you can't use: print(f"{a * 3}".format(a=2)). +1
6

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

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

5 Comments

@AlirezaAfzalaghaei Although I admit haven't tried every way, I'm pretty sure you can't. The whole purpose of using f-strings is to avoid the str.format method. Also, you never made it clear you had to use the str.format method. Please state all your requirements in your question before hand next time.
@Alireza Afzal aghaei print(f"{a * 3}".format(a=2)) does work but what's the purpose of the f-strings then?
@whiteredblack I thought so to, but that's not the case. Running print(f"{a * 3}".format(a=2)) raises NameError: name 'a' is not defined.
Ok, Actually i can't create any variable. Also i said using format in question title :)
In [20]: a=2 In [21]: print(f"{a * 3}".format(a=3)) what would you expect 9..sorry its 6
0

You can try this.

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

3 Comments

as i said a wont use eval (or int or float for ...) functions!
ohh k, you just mentioned eval in your question.
Actually, you didn't say anything about int or float functions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.