splor-mg / notas

Base de conhecimento
https://splor-mg.github.io/notas/main
0 stars 0 forks source link

python tip: use f-strings, though not always #34

Open fjuniorr opened 7 months ago

fjuniorr commented 7 months ago

Dica da newsletter python morsels útil para https://github.com/splor-mg/atividades/issues/81.

====

Using f-strings is typically preferable over the format method because f-strings are often more readable. But the string format method can still be quite handy sometimes.

For example, if we wanted to separate the definition of a string template from the usage of that template, we could use the format method:

BASE_URL = "https://api.stackexchange.com/2.3/questions/{ids}?site={site}"

question_ids = ["33809864", "2759323", "9321955"]
url_for_questions = BASE_URL.format(
    site="stackoverflow",
    ids=";".join(question_ids),
)

We can't use an f-string for that situation because f-strings evaluate their expression immediately (whereas the format method can be called on a string at a later time).