Python String Formatting

String formatting in Python allows you to create strings that include variable values, making your output more dynamic and readable. Python offers several ways to format strings, including the % operator, the str.format() method, and f-strings (formatted string literals).


String Formatting Methods

Python provides multiple ways to format strings, each with its own syntax and use cases:

  1. Using the % Operator
  2. Using the str.format() Method
  3. Using f-strings (Formatted String Literals)




1. Using the % Operator

The % operator is one of the oldest methods of string formatting in Python. It uses format specifiers to insert values into a string.

Syntax

"Hello, %s!" % name

Example

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




2. Using the str.format() Method

The str.format() method provides a more powerful way to format strings. It uses curly braces {} as placeholders for the values to be inserted.

Syntax

"Hello, {}!".format(name)

Example

name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))

You can also use positional and keyword arguments within the placeholders:

print("My name is {0} and I am {1} years old.".format(name, age))
print("My name is {name} and I am {age} years old.".format(name="Alice", age=30))




3. Using f-strings (Formatted String Literals)

Introduced in Python 3.6, f-strings provide a concise and readable way to include expressions inside string literals. They are prefixed with f or F and use curly braces {} to evaluate variables and expressions.

Syntax

f"Hello, {name}!"

Example

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

You can also include expressions inside the curly braces:

print(f"In two years, I will be {age + 2} years old.")




Python Labs

Scroll to Top