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
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"` .