Python

String Formatting in Python is the process of dynamically inserting values into a string. It allows you to create templates for text where specific parts can be replaced by variables, expressions, or function results.

In modern Python, there are three primary ways to format strings, each representing an evolution in the language's syntax.

1. Theoretical Overview

Why use String Formatting?

  • Readability: It is much cleaner than using "string concatenation" (joining strings with +).

  • Precision: You can control how numbers are displayed (e.g., rounding decimals).

  • Data Injection: It allows you to build complex messages, like automated emails or UI labels, using dynamic data.

The Three Evolution Stages

  1. Old Style (% Operator): The original way, inherited from C-style programming.

  2. New Style (.format() method): Introduced in Python 2.6 to provide more power and flexibility.

  3. f-Strings (Literal String Interpolation): Introduced in Python 3.6. It is the fastest and most readable method available today.

2. Code Implementation

A. f-Strings (The Modern Standard)

f-strings are defined by prefixing a string with f or F. You place variables or expressions directly inside curly braces {}.

Python
name = "Admin"
score = 95.567

# Basic usage
print(f"Hello, {name}!")

# Expressions inside braces
print(f"Next year, you will be {20 + 1} years old.")

# Number formatting (Round to 2 decimal places)
print(f"Your score is {score:.2f}") 

B. The .format() Method

This method uses placeholders {} within a string and passes arguments into the .format() function.

Python
animal = "dog"
action = "barks"

# Positional formatting
print("The {} {}.".format(animal, action))

# Index-based formatting
print("The {1} {0}.".format(action, animal))

# Named placeholders
print("User: {user}, Role: {role}".format(user="Arjun", role="Instructor"))

C. The % Operator (Legacy)

Though less common now, you will still see this in older codebases.

Python
# %s for string, %d for integer, %f for float
name = "EMBLAb"
print("Welcome to %s" % name)

3. Formatting Numbers and Alignment

String formatting is particularly powerful when you need to align text in tables or format currency.

FeatureCode ExampleOutput
Decimal placesf"{3.14159:.2f}"3.14
Padding (Width)f"{'Hi':>10}" Hi (Right align)
Percentagef"{0.25:.0%}"25%
Thousands Sepf"{1000000:,}"1,000,000

4. Best Practices

  • Always use f-strings if you are using Python 3.6 or higher. They are more concise and execute faster than .format().

  • Use .format() only if you need to support very old versions of Python or if the formatting string is being passed as a variable from an external source.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now