0

In JavaScript I can use a template literal and include calculate values. For example:

var a = 3;
var b = 8;
var text = `Adding ${a} + ${b} = ${a+b}`;   //  Adding 3 + 8 = 11

I know python has f'…' strings and str.format() with placeholder. Is there a way I can include a calculation in the string?

2
  • Simply f'{a} + {b} = {a + b}' will do - That is basically like a,"+",b,"=",a+b Commented Aug 12, 2021 at 3:06
  • f-strings support embedded calculations. What did you try? Commented Aug 12, 2021 at 3:34

2 Answers 2

5

Using f-string:

a = 3
b = 8    
text = f'{a} + {b} = {a + b}'

The text variable in this case is a string containing '3 + 8 = 11'.

Using str.format:

a = 3
b = 8
text = '{0} {1} = {2}'.format(a, b, a + b)
Sign up to request clarification or add additional context in comments.

6 Comments

Yes, that works. Is this possible using str.format()?
@Manngo Yes, it's possible, please refer to this thread for an example.
Probably '{a} + {b} = {a + b}'.format(**{'a': a, 'b': b, 'a + b': a + b}). but this is very much a bunch of repeated tokens. Just use f-strings.
From the str.format docs, it can be both *args or **kwargs, so using positional args is less verbose (for simplicity)
So, the answer appears to be that the expression in the .format() method {…} is strictly a key, not an evaluated expression. On the other hand, in the f-string, it is evaluated.
|
1

Using str.format:

a = 3
b = 8    
text = '{0} + {1} = {2}'.format(a,b,a+b)
print(text)

Using f-string:

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

All of them do the same thing as:

a,"+",b,"=",a+b

1 Comment

The tokens for .format has been changed and differs from the intent of the OP's question (they should be provided as names). Please refer to this thread for what should be done instead (i.e. pass in a series of keywords).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.