Python String Formatting


String formatting lets you add variables, values and expressions inside a string in a clean and readable way. Instead of joining text using the + operator or writing long repetitive statements, Python gives you several formatting methods that make your output look organised and professional.

In this tutorial, you will learn different ways to format strings in Python, including f-strings, format(), placeholders, alignment options, number formatting and real-life examples that show where string formatting is important.

What Is String Formatting?

String formatting means inserting values into a string in a structured way. You choose a format and Python fills in the values automatically.

For example:

  • Showing prices

  • Displaying user information

  • Formatting dates

  • Printing results in a clean layout

  • Creating reports

String formatting helps you write clean output and improves readability.

Using f-Strings (Fastest and Easiest)

f-strings were introduced in Python 3.6 and are the best and most readable way to format strings. You add an f before the string and write expressions inside {}.

Example:

name = "Aarohi"
age = 20

print(f"My name is {name} and I am {age} years old.")

This produces:

My name is Aarohi and I am 20 years old.

You can even write expressions inside:

print(f"Next year I will be {age + 1}.")

Using the format() Method

Before f-strings, Python used the format() method. You place {} in the string and pass the values into the method.

Example:

name = "Aarohi"
city = "Delhi"

text = "My name is {} and I live in {}.".format(name, city)
print(text)

You can also use numbered placeholders:

"Name: {0}, City: {1}".format(name, city)

Or named placeholders:

"Name: {n}, City: {c}".format(n=name, c=city)

Using the % Operator (Older Method)

This is an older formatting style but still used in some codebases.

Example:

name = "Aarohi"
age = 20

print("My name is %s and I am %d years old." % (name, age))

Here:

  • %s → string

  • %d → integer

  • %f → float

This method is mostly used for compatibility with older programs.

Formatting Numbers

String formatting becomes important when working with numbers.

Formatting decimal places

price = 99.567
print(f"Price: {price:.2f}")

Output:

Price: 99.57

Adding commas

salary = 1500000
print(f"Salary: {salary:,}")

Output:

Salary: 1,500,000

Formatting percentages

score = 0.85
print(f"Score: {score:.0%}")

Output:

85%

Aligning Text

You can align text left, right or center to create clean layouts.

Left alignment

print(f"{'Python':<10} is fun")

Right alignment

print(f"{'Python':>10} is fun")

Center alignment

print(f"{'Python':^10}")

These are useful when creating tables or structured reports.

Combining Text With Calculations

f-strings allow direct expressions inside {}.

Example:

marks = 88
print(f"Your score is {marks / 100 * 100}%")

You don’t need separate variables for simple calculations.

Formatting Dates With f-Strings

Example:

from datetime import datetime

today = datetime.now()
print(f"Today is {today:%d-%m-%Y}")

This prints the date in a clean format.

Using format() With Alignment and Width

You can control width:

print("{:10} {:10}".format("Name", "City"))
print("{:10} {:10}".format("Aarohi", "Delhi"))

This creates a table-like structure.

Real-Life Example: Billing System

Imagine you need a formatted bill:

item = "Laptop"
price = 79999.99

print(f"Item: {item}")
print(f"Price: ₹{price:,.2f}")

Output:

Item: Laptop
Price: ₹79,999.99

This looks clean and professional.

Real-Life Example: User Profile Display

name = "Aarohi"
age = 20
city = "Mumbai"

print(f"Profile: {name}, Age: {age}, City: {city}")

String formatting is widely used in applications, dashboards, forms and website output.

Practical Examples

  1. Simple f-string

f"Hello {name}"
  1. Math inside f-string

f"Total: {10 + 5}"
  1. Decimal formatting

f"{value:.3f}"
  1. Thousands comma

f"{num:,}"
  1. Percentage

f"{score:.1%}"
  1. Left alignment

f"{text:<15}"
  1. Right alignment

f"{text:>15}"
  1. Center alignment

f"{text:^15}"
  1. Using format()

"Name: {}".format(name)
  1. Using % operator

"%s is %d years old" % (name, age)

Summary of the Tutorial

String formatting helps you add values, variables and expressions inside strings in a clear and organised way. You learned how to use f-strings, format(), the % operator, alignment options, number formatting and real-life uses. f-strings are the most modern and readable method, but all styles are useful depending on your requirement.


Practice Questions

Q1. Write a Python program to print "Hello, my name is Alice" using the .format() method.

Q2. Write a Python program to use keyword arguments with .format() to insert a name and age into a sentence.

Q3. Write a Python program to display the number 3.4567 rounded as 3.46 using string formatting.

Q4. Write a Python program to print 007 using string formatting to keep leading zeros.

Q5. Write a Python program to use an f-string to show a total score stored in a variable.

Q6. Write a Python program to print a centered title using the ^ alignment symbol in string formatting.

Q7. Write a Python program to format a table with aligned text and numeric values using formatting specifiers.

Q8. Write a Python program to escape curly braces in a string and display {Hello}.

Q9. Write a Python program to combine a string and an integer using string formatting.

Q10. Write a Python program to format a price to 2 decimal places and prefix it with a $ symbol.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top