How to do string interpolation in Python?

2

For example, in PHP we can do this:

$preco = 200;
$unidades = 10;

$texto_final = "O produto custa {$preco} reais e restam {$unidades} unidades.";

Is it possible to do something similar in Python or do I need to concatenate always?

    
asked by anonymous 22.12.2017 / 07:10

2 answers

4

For versions prior to 3.6, always prefer to use the str.format method and I explain the reason for this question:

Character formatting

Already, since version 3.6, a new way of performing the interpolation has been added: as f-strings ( PEP 498 ). They are strings defined with the prefix f and can contain expressions between keys that will be parsed at runtime.

preco = 200
unidades = 10

print(f"O produto custa {preco} reais e restam {unidades} unidades.")

See working at Repl.it

You can even use the training rules that the str.format method has, such as:

pi = 3.14159

print(f'O valor de pi é {pi: >10.3}')

See working at Repl.it

    
22.12.2017 / 12:17
3

You can do this:

preco = 200
unidades = 10

texto_final = "O produto custa R$ %.2f reais e restam %s unidades." % (preco, unidades)

print(texto_final)

# Outros exemplos

nome = 'Thon';
sobre = 'de Souza';

print("%s %s" % (nome, sobre))

print("{} {}".format(nome, sobre))
print("{nome} {sobre}".format(nome="João", sobre="da Silva"))
print("{sobre} {nome}".format(nome="João", sobre="da Silva"))

preco = 162.58

print("R$ %.1f" % (preco))
print("R$ %.2f" % (preco))
print("R$ %.3f" % (preco))
  • % s - String (or any object with a string representation, such as numbers)
  • % d - Integers
  • % f - Floating-point numbers
  • %. - Number of floating points with a fixed number of digits to the right of the point.
  • % x /% X - Integer hexadecimal representation (lowercase / uppercase)
  

See working at repl.it

References

22.12.2017 / 07:33