Format Strings

3 min read ·

String formatting in Python is used to insert variables and expressions inside strings in a clean and readable way. It helps create dynamic output messages without complex concatenation.
Python provides multiple methods for formatting strings, from basic to modern.

What Is String Formatting?

String formatting allows you to:
  • Combine text and variables
  • Display values inside strings
  • Control output format
Definition

String formatting is the process of embedding values inside a string.


Format Strings Using f-Strings (Recommended)

f-strings are the modern and most preferred way to format strings in Python. They were introduced in Python 3.6.

Syntax

Code Example 1: Basic f-string

Code Example 2: Multiple Variables

Code Example 3: Expression Inside f-string

Best Practice

Always use f-strings for clean and readable formatting.


Format Strings Using format() Method

The format() method is an older but still valid way to format strings.

Code Example 1: Single Placeholder

Code Example 2: Multiple Placeholders

Code Example 3: Indexed Placeholders


Format Strings Using Named Placeholders

You can use named placeholders with the format() method.

Old Style Formatting (% Operator)

This is the oldest method of string formatting in Python. It is still supported but not recommended for new code.

Code Example 1: String Formatting

Code Example 2: Integer Formatting

Code Example 3: Multiple Values

Note

Avoid % formatting in modern Python code.


Formatting Numbers in Strings

Python allows formatting numbers easily.

Code Example 1: Decimal Places

Code Example 2: Padding Numbers

Code Example 3: Percentage Format


Multiline Format Strings

f-strings work perfectly with multi-line strings.

Common Mistakes

Mixing + Instead of Formatting

Better approach:

Exercise

  • Format your name and age using f-string
  • Print sum of two numbers inside a string
  • Format a float value to 2 decimal places