How to interpolate string in Python?

Asked

Viewed 5,568 times

8

For example, in PHP, we can do so:

$preco = 200;
$unidades = 10;

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

You can do something similar in Python or you must always concatenate?

2 answers

7


For versions prior to 3.6, always use the method str.format and I explain why in this question:

Already, from version 3.6, a new way to perform the interpolation has been added: the f-strings (PEP 498). They are strings defined with the prefix f and may 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 on Repl.it

It is also permitted to use the training rules which the method str.format possesses, such as:

pi = 3.14159

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

See working on Repl.it

6

You can do it like 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 - Whole
  • %f - Floating point numbers
  • %.<digit number>f - Floating point numbers with a fixed number of digits to the right of the point.
  • %x/%X - Integers in hexadecimal representation (lower case / upper case)

See working on repl it.

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.