Search code examples
pythonstringf-string

Formatted string with calculated values in Python


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?


Solution

  • 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)