Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Strings & text processingJuniorVery commonPractical

What are the three main ways to format strings in Python, and why are f-strings now preferred?

Answer

The three approaches are old `%`-style formatting (`"%s is %d" % (name, age)`), the `.format()` method (`"{} is {}".format(name, age)`), and f-strings (`f"{name} is {age}"`), introduced in Python 3.6. F-strings are preferred because the expressions are evaluated inline where they are written, which is more readable, they support the same format-spec mini-language as `.format()`, and they can call methods and even nested expressions directly. F-strings are also commonly the fastest of the three in typical CPython benchmarks, but that gap depends on the Python version and what exactly is being formatted, so readability is the more durable reason to prefer them.

Strong answer includes

  • percent formatting, .format(), and f-strings
  • f-strings embed expressions inline for readability
  • f-strings introduced in 3.6, usually fastest in benchmarks but that is not a language guarantee

Practical example

Python example
f"{price:,.2f}"

formats a float with thousands separators and two decimal places directly inside the string literal, e.g. turning `1234.5` into `"1,234.50"` .

#strings#formatting

Sources

The Python TutorialPython Software Foundation · Baseline syntax, control flow, functions and module basicsWhat's new in Python 3.14Python Software Foundation · Current-version language and runtime changes, including template strings and free-threading support