MyInternships.in

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.

Basic f-strings
Python
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.

Formatting numbers
Python
price = 1234.5678
rate = 0.856

print(f"{price:.2f}")
print(f"{price:,.2f}")
print(f"{rate:.1%}")
Output
Output
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.

Aligning text
Python
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).

Debug specifier
Python
x = 42
y = x * 2
print(f"{x=} {y=}")
Output
Output
x=42 y=84

f-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.

Featuref-string.format()
Syntaxf"{name}""{}".format(name)
ReadabilityHigh — variable inlineLower — separate from text
Expressions insideYes, e.g. f"{a+b}"Limited, needs pre-computed vars
Introduced inPython 3.6Python 2.6
💡

Prefer f-strings for all new code — they are faster and more readable than both .format() and the old % operator.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships