Nearby lessons

53 of 109

Python - String Formatting

Overview

String formatting is used to insert values into strings dynamically and create readable, user-friendly output.

It helps avoid manual string concatenation and keeps output consistent.

Ways to Format Strings

  • Using the % operator
  • Using the format() method
  • Using f-strings

% Operator

The old-style formatting method uses specifiers such as %s, %d, and %f.

You can also limit decimal places using syntax like %.2f.

🐍Code Cell
1name = 'Rahul'
2age = 25
3 
4print('Name: %s Age: %d' % (name, age))
Output
Name: Rahul Age: 25

format() Method

format() is a modern and flexible method for string formatting.

It also supports indexed placeholders and alignment controls.

🐍Code Cell
1name = 'Rahul'
2age = 25
3 
4print('Name: {} Age: {}'.format(name, age))
Output
Name: Rahul Age: 25

f-Strings

f-strings were introduced in Python 3.6 and provide the cleanest syntax for formatting.

f-strings can also evaluate expressions directly inside the braces.

🐍Code Cell
1name = 'Rahul'
2age = 25
3 
4print(f'Name: {name} Age: {age}')
Output
Name: Rahul Age: 25

Common Formatting Features

  • Decimal control for floats
  • Left, right, and center alignment
  • Expression evaluation inside f-strings
  • Thousands separators and percentage formatting

These features make formatted output easier to read and present.

Quick Comparison

Method Style
% operator Old style
format() Flexible and readable
f-string Modern, clean, and fast

🧠 Test Your Knowledge

8 Questions

Progress: 0 / 8