Python – String Format
String formatting in Python allows you to create dynamic, readable, and structured text by inserting variables into strings. It’s a powerful tool for displaying messages, logging, and generating user-friendly outputs.
In this tutorial, you’ll learn the most common and effective string formatting methods:
format()
method- f-strings (formatted string literals)
%
formatting (legacy)
Why Format Strings?
Instead of this:
name = "Alice"
age = 25
print("My name is " + name + " and I am " + str(age) + " years old.")
Use formatting:
print(f"My name is {name} and I am {age} years old.")
Much cleaner and more readable!
Method 1: format()
Method
This method uses curly braces {}
as placeholders and .format()
to fill them.
Basic Example:
name = "Alice"
print("Hello, {}".format(name)) # Output: Hello, Alice
Multiple Variables:
name = "Bob"
age = 30
print("Name: {}, Age: {}".format(name, age))
Positional Indexing:
print("I like {1} more than {0}".format("Java", "Python"))
# Output: I like Python more than Java
Named Placeholders:
print("My name is {first} {last}".format(first="John", last="Doe"))
Method 2: f-Strings (Python 3.6+)
f-strings (formatted string literals) are the most modern and preferred method for string formatting.
Basic Example:
name = "Eve"
age = 28
print(f"My name is {name} and I am {age} years old.")
Expressions Inside f-Strings:
price = 49.99
quantity = 3
print(f"Total: ${price * quantity:.2f}")
# Output: Total: $149.97
✅ Cleaner, faster, and supports inline expressions.
Method 3: %
Operator (Old Style)
This is the legacy way of formatting strings (similar to C-style formatting).
Basic Example:
name = "Alice"
print("Hello, %s" % name)
With Multiple Variables:
name = "Bob"
age = 25
print("Name: %s, Age: %d" % (name, age))
Format Code
Format Code | Description |
---|---|
%s | String |
%d | Integer |
%f | Floating point |
⚠️ Use this method only if you're maintaining older Python code.
Formatting Numbers
Decimal Precision:
pi = 3.14159
print(f"Value of Pi: {pi:.2f}") # Output: 3.14
Padding and Alignment:
text = "Hi"
print(f"{text:>10}") # Right-align in 10 spaces
Summary Table
Method | Syntax Example | Python Version |
---|---|---|
.format() | "Hello {}".format(name) | 2.7+ |
f-string | f"Hello {name}" | 3.6+ |
% operator | "Hello %s" % name | Legacy |