Python

Python Basics

Data Structures in Python

Control Flow and Loops

Functions and Scope

Object-Oriented Programming (OOP)

Python Programs

String Formatting in Python

String formatting allows you to create dynamic strings by inserting variables, expressions, or formatted values into predefined text. Python offers three main methods:

  1. f-strings (Python 3.6+) – Modern and easiest
  2. str.format() method – Flexible and powerful
  3. % operator (old-style) – Legacy but still used

Let’s explore each method in detail.


1. f-strings (Formatted String Literals)

Introduced in Python 3.6, f-strings provide the simplest and most readable way to format strings.

Basic Syntax:

f"Text {variable} more text"

Examples:

Inserting Variables

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

Output:

My name is Alice and I am 25 years old.

Expressions Inside f-strings

a, b = 10, 20
print(f"The sum of {a} and {b} is {a + b}.")

Output:

The sum of 10 and 20 is 30.

Formatting Numbers

price = 49.9876
print(f"Price: ${price:.2f}") # Rounds to 2 decimal places

Output:

Price: $49.99

Advantages of f-strings:

Clean and readable
Supports expressions
Fast execution


2. str.format() Method

The format() method is versatile and works in all Python versions.

Basic Syntax:

"Text {} more text".format(value)

Examples:

Positional Formatting

print("Hello, {}!".format("Alice"))

Output:

Hello, Alice!

Index-Based Formatting

print("{0} loves {1} and {1} loves {0}.".format("Alice", "Bob"))

Output:

Alice loves Bob and Bob loves Alice.

Named Placeholders

print("Name: {name}, Age: {age}".format(name="Alice", age=25))

Output:

Name: Alice, Age: 25

Number Formatting

print("Value: {:.2f}".format(3.14159)) # Rounds to 2 decimal places

Output:

Value: 3.14

Advantages of format():

Works in all Python versions
Supports named and positional arguments
More control over formatting


3. % Operator (Old-Style Formatting)

This is the oldest method, inspired by C’s printf().

Basic Syntax:

"Text %s more text" % value

Examples:

String and Integer Formatting

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

Output:

My name is Alice and I am 25 years old.

Floating-Point Precision

pi = 3.14159
print("Pi rounded to 2 decimals: %.2f" % pi)

Output:

Pi rounded to 2 decimals: 3.14

Common Format Specifiers:

SpecifierMeaningExample (% usage)
%sString"Name: %s" % "Alice"
%dInteger"Age: %d" % 25
%fFloat"Price: %.2f" % 49.99
%xHexadecimal"Hex: %x" % 255ff

Disadvantages of % Operator:

Less readable
Limited functionality
Not recommended for new code


Comparison of String Formatting Methods

Featuref-stringsformat()% Operator
Readability⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Speed⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Python Version3.6+AllAll
Expression SupportYesNoNo

Recommendation:

  • Use f-strings for Python 3.6+ (best readability & performance).
  • Use format() for compatibility with older Python versions.
  • Avoid % operator in new code.

Practical Use Cases

1. Dynamic SQL Queries (f-strings)

user_id = 100
query = f"SELECT * FROM users WHERE id = {user_id}"
print(query)

2. Logging Messages (format())

error_code = 404
log_message = "Error {}: Page not found".format(error_code)
print(log_message)

3. Legacy Code Maintenance (% Operator)

# Old code (still seen in some scripts)
print("User: %s, Score: %d" % ("Alice", 95))

Common Mistakes to Avoid

  1. Mismatched Placeholders & Variables

    # Wrong
    print("{} {}".format("Alice")) # Missing argument
  2. Incorrect Format Specifiers

    # Wrong
    print("Age: %s" % 25.5) # Should use %f for floats
  3. Overcomplicating Simple Cases

    # Unnecessary
    print("Name: " + name + ", Age: " + str(age))
    # Better
    print(f"Name: {name}, Age: {age}")

Python offers multiple ways to format strings:

  • f-strings (best for modern Python)
  • format() (flexible and backward-compatible)
  • % operator (old-style, avoid in new code)

Key Takeaways:

f-strings are the cleanest and fastest option.
format() is useful for complex formatting.
% operator is outdated but still seen in legacy code.

Start using f-strings for better readability and efficiency in your Python projects! 🚀