Python String Formatting

String formatting in Python allows you to create strings that include variable values, making your output more dynamic and readable. Python offers several ways to format strings, including the % operator, the str.format() method, and f-strings (formatted string literals).

String Formatting Methods

Python provides multiple ways to format strings, each with its own syntax and use cases:

  1. Using the % Operator
  2. Using the str.format() Method
  3. Using f-strings (Formatted String Literals)

1. Using the % Operator

The % operator is one of the oldest methods of string formatting in Python. It uses format specifiers to insert values into a string.

Tutorials dojo strip

Syntax

Python

Example

Python

2. Using the str.format() Method

The str.format() method provides a more powerful way to format strings. It uses curly braces {} as placeholders for the values to be inserted.

Syntax

Python

Example

Python

You can also use positional and keyword arguments within the placeholders:

Python

3. Using f-strings (Formatted String Literals)

Introduced in Python 3.6, f-strings provide a concise and readable way to include expressions inside string literals. They are prefixed with f or F and use curly braces {} to evaluate variables and expressions.

Syntax

Python

Example

Python

You can also include expressions inside the curly braces:

Python

Python Labs

Tutorials dojo strip