Python Basics

String Formatting in Python

f-strings put variables and expressions straight into text, and a format specifier after a colon controls decimals, width, alignment and separators.

What is String Formatting?

f-strings put variables and expressions straight into text, and a format specifier after a colon controls decimals, width, alignment and separators.

Build readable output with Python f-strings and format specifiers.

When should you use it?

  • Learn Python syntax through a practical example.
  • Build a foundation for larger programming problems.
  • Test an idea quickly without a local setup.

Example code

Run code →
main.py
name = "Lin"
score = 92.456
items = 3

# f-strings put expressions inside {} directly in the text.
print(f"{name} scored {score} points")

# Format specifiers after a colon control how values look.
print(f"Rounded: {score:.1f}")
print(f"Price: ${19.5:.2f}")
print(f"Padded: [{items:>5}] [{items:<5}] [{items:^5}]")
print(f"Thousands: {1234567:,}")
print(f"Percent: {0.875:.0%}")

# Any expression works, including calls and arithmetic.
print(f"{name.upper()} has {items * 2} tickets")

# A table with aligned columns.
for product, price in [("Tea", 2.5), ("Coffee", 3.75)]:
    print(f"{product:<8}{price:>6.2f}")

Expected output

Lin scored 92.456 points
Rounded: 92.5
Price: $19.50
Padded: [    3] [3    ] [  3  ]
Thousands: 1,234,567
Percent: 88%
LIN has 6 tickets
Tea       2.50
Coffee    3.75

How it works

.1f rounds to one decimal, >5 and <5 align inside five characters, , adds thousands separators and .0% shows a fraction as a percentage.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in Python IDE →

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges