String Formatting in Python

String formatting allows you to create formatted strings by inserting variables or expressions into a string. Python provides several ways to format strings, including the f-string, format() method, and the old-style % formatting.

Using f-Strings (Python 3.6+):

Python
name = "Alice"
age = 30
greeting = f"Hello, {name}. You are {age} years old."
print(greeting)

# Output: Hello, Alice. You are 30 years old.

Using str.format() Method:

The format() method allows you to insert values into a string:

Python
name = "Bob"
age = 25
greeting = "Hello, {}. You are {} years old.".format(name, age)
print(greeting)

# Output: Hello, Bob. You are 25 years old.

Using Old-Style % Formatting:

Old-style string formatting uses the % operator:

Python
name = "Charlie"
age = 35
greeting = "Hello, %s. You are %d years old." % (name, age)
print(greeting)

# Output: Hello, Charlie. You are 35 years old.

Formatting Numbers:

You can format numbers with specific precision or padding:

Python
# Formatting with two decimal places
pi = 3.14159
formatted_pi = f"Pi to two decimal places: {pi:.2f}"
print(formatted_pi)  # Output: Pi to two decimal places: 3.14

# Padding numbers with leading zeros
number = 42
formatted_number = f"Number with leading zeros: {number:05d}"
print(formatted_number)  # Output: Number with leading zeros: 00042

String formatting is a powerful feature in Python that allows you to create well-formatted, readable output.