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?

Manngo
  • 14,066
  • 10
  • 88
  • 110

2 Answers2

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)
luizbarcelos
  • 686
  • 5
  • 17
  • Yes, that works. Is this possible using `str.format()`? – Manngo Aug 12 '21 at 03:10
  • @Manngo Yes, it's possible, please refer to [this thread for an example](https://stackoverflow.com/questions/6229671/how-to-use-str-format-with-a-dictionary-in-python). – metatoaster Aug 12 '21 at 03:14
  • 1
    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. – metatoaster Aug 12 '21 at 03:19
  • From the [`str.format` docs](https://docs.python.org/3/library/stdtypes.html#str.format), it can be both `*args` or `**kwargs`, so using positional args is less verbose (for simplicity) – luizbarcelos Aug 12 '21 at 03:24
  • 1
    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. – Manngo Aug 12 '21 at 03:35
  • @Manngo correct; f-strings in Python is the template string analogue in Node.js/JavaScript (analogue due to certain differences as some of the Python's `.format()` conventions are carried over, which are absent in Node.js/JavaScript). The expression in `.format()` follows the arguments and/or keys specified, which is [documented](https://docs.python.org/3.8/library/stdtypes.html#str.format) briefly - follow the Format String Syntax link in there for further documentation. – metatoaster Aug 12 '21 at 04:06
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
    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](https://stackoverflow.com/questions/6229671/how-to-use-str-format-with-a-dictionary-in-python) for what should be done instead (i.e. pass in a series of keywords). – metatoaster Aug 12 '21 at 03:15