Python Advanced
Python f-strings
f-strings are the modern, readable way to build strings in Python by embedding variables and expressions directly inside curly braces.
Basic f-string Syntax
Add an f right before the opening quote, then place any variable or expression inside curly braces. Python evaluates the expression and inserts the result directly into the string at that position.
name = "Priya"
score = 87
print(f"Hello {name}, you scored {score} marks")
print(f"Next year you'll be {score + 1} points wiser")Number Formatting
You can control how numbers appear by adding a colon and a format spec after the expression, for example limiting decimal places, adding thousands separators, or showing percentages.
price = 1234.5678
rate = 0.856
print(f"{price:.2f}")
print(f"{price:,.2f}")
print(f"{rate:.1%}")1234.57
1,234.57
85.6%Alignment and Width
You can pad and align text inside a fixed width using < for left, > for right, and ^ for center alignment, useful when printing neat tables in the terminal.
for item in ["Pen", "Notebook", "Bag"]:
print(f"{item:<10}| in stock")The Debug Specifier (=)
Since Python 3.8, adding = right after an expression prints both the expression text and its value, which is extremely handy for quick debugging without writing print("x =", x).
x = 42
y = x * 2
print(f"{x=} {y=}")x=42 y=84f-strings vs .format()
Before f-strings, Python developers used the .format() method, which works but is more verbose. f-strings are now the preferred style because they are shorter and easier to read.
| Feature | f-string | .format() |
|---|---|---|
| Syntax | f"{name}" | "{}".format(name) |
| Readability | High — variable inline | Lower — separate from text |
| Expressions inside | Yes, e.g. f"{a+b}" | Limited, needs pre-computed vars |
| Introduced in | Python 3.6 | Python 2.6 |
Prefer f-strings for all new code — they are faster and more readable than both .format() and the old % operator.
