String Formatting Operator in Python

In Python, the string formatting operator (%) is used to format strings by embedding variables or expressions within the string. This operator is particularly useful for creating dynamic strings that combine both static text and variable data.

Key Points on String Formatting Operator:

Syntax of String Formatting Operator:

Syntax Example

formatted_string = "Hello, %s! You are %d years old." % ("Alice", 30)

Example of String Formatting Operator in Python:

This example demonstrates basic string formatting with name and age variables.

Code Example 1

name = "Alice"
        age = 30
        print("Hello, %s! You are %d years old." % (name, age))

Output for Code Example 1:

Hello, Alice! You are 30 years old.

Example with Floating-Point Precision:

This example demonstrates how to format a floating-point number with two decimal places.

Code Example 2

price = 49.99
        print("The price is $%.2f" % price)

Output for Code Example 2:

The price is $49.99

Example with Multiple Variables:

This example uses multiple variables to create a formatted message about a person.

Code Example 3

name = "Bob"
        age = 25
        height = 5.9
        print("%s is %d years old and %.1f feet tall." % (name, age, height))

Output for Code Example 3:

Bob is 25 years old and 5.9 feet tall.

Detailed Explanation:

Mastering the string formatting operator helps developers create readable, dynamic messages in Python, especially in versions prior to Python 3.6.