Basic String Formatting in Python

String formatting is an essential skill in Python, allowing you to dynamically insert variables and expressions into strings. Python supports multiple ways to format strings, each with its own use cases.


The % Operator

The % operator is an older way to format strings, reminiscent of C-style formatting.

Example:

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

Output:

My name is Alice and I am 30 years old.

Format Specifiers:

  • %s: String
  • %d: Integer
  • %f: Float
  • %.2f: Float with two decimal places
Warning

The % operator is considered outdated and less readable compared to newer methods. Use it only for legacy code.


The str.format() Method

Introduced in Python 3, the str.format() method provides a more versatile and readable way to format strings.

Example:

name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)

Output:

My name is Bob and I am 25 years old.

Positional and Keyword Arguments:

# Positional arguments
"{0} is {1} years old.".format("Charlie", 35)

# Keyword arguments
"{name} is {age} years old.".format(name="Daisy", age=40)

Advanced Formatting:

value = 123.4567
print("The value is {:.2f}".format(value))

Output:

The value is 123.46
Info

Use str.format() for Python versions below 3.6 where f-strings are not supported.


Introduced in Python 3.6, f-strings (formatted string literals) offer the most concise and readable way to format strings.

Syntax:

name = "Eve"
age = 28
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)

Output:

My name is Eve and I am 28 years old.

Inline Expressions:

radius = 5
area = 3.14159 * radius**2
print(f"The area of a circle with radius {radius} is {area:.2f}")

Output:

The area of a circle with radius 5 is 78.54
Deep Dive

F-strings are both faster and more readable compared to other methods. They are ideal for modern Python code.


Comparison of Methods

Feature% Operatorstr.format()F-Strings
ReadabilityLowModerateHigh
SpeedModerateModerateHigh
Python Version SupportLegacyPython 3+Python 3.6+
Under Construction

Consider using f-strings in all new Python code to maintain readability and performance.

Task

Practice: String Formatting Examples

  1. Use the % operator to format the following string:

    • Name: "Frank"
    • Age: 45

    Example:

    name = "Frank"
    age = 45
    print("Name: %s, Age: %d" % (name, age))
    
  2. Format a string with str.format() to display a price with two decimal places:

    • Price: 19.995

    Example:

    price = 19.995
    print("The price is {:.2f}".format(price))
    
  3. Use f-strings to display the square of a number:

    • Number: 8

    Example:

    number = 8
    print(f"The square of {number} is {number**2}")
    

Copyright © 2025 Devship. All rights reserved.

Made by imParth