- Syntax
- Example 1: Formatting a String
- Example 2: Formatting an Integer
- Example 3: Formatting a Floating-Point Number
- Example 4: Limiting Decimal Places
- Example 5: Formatting Multiple Values
- Example 6: User Input
- Example 7: Printing a Percent Sign
- Example 8: Formatting a Character
- Example 9: Mixing Different Data Types
- Example 10: Checking the Result Type
- Common Mistakes
- Best Practices
- Key Points to Remember
String formatting is the process of inserting values into a string to create meaningful output.
Before the introduction of str.format() and f-strings, Python commonly used the % operator for string formatting. This style is known as printf-style formatting because it is similar to the printf() function in the C programming language.
The % operator replaces format specifiers such as %s, %d, and %f with actual values.
Although modern Python code often uses f-strings, you may still encounter % formatting in older codebases, making it important to understand.
Syntax #
"format string" % value
For multiple values:
"format string" % (value1, value2, value3)
Common Format Specifiers #
| Specifier | Description |
|---|---|
%s |
String |
%d |
Integer |
%f |
Floating-point number |
%.2f |
Floating-point number with 2 decimal places |
%c |
Single character |
%% |
Prints the % character |
Example 1: Formatting a String #
main.py
name = "Alice"
print("Hello, %s!" % name)
Output #
Hello, Alice!
Explanation #
%sis the placeholder for a string.- The value of
namereplaces%s. - The formatted string is printed.
Example 2: Formatting an Integer #
main.py
age = 21
print("Age: %d" % age)
Output #
Age: 21
Explanation #
%dis used for integers.- The integer value replaces the placeholder.
- The output displays the formatted integer.
Example 3: Formatting a Floating-Point Number #
main.py
price = 49.95
print("Price: %f" % price)
Output #
Price: 49.950000
Explanation #
%fformats a floating-point number.- By default, six digits are displayed after the decimal point.
- Python automatically formats the number.
Example 4: Limiting Decimal Places #
main.py
pi = 3.14159265
print("Pi = %.2f" % pi)
Output #
Pi = 3.14
Explanation #
%.2fdisplays two digits after the decimal point.- Python rounds the value automatically.
- This format is useful for displaying measurements and financial values.
Example 5: Formatting Multiple Values #
main.py
name = "John"
age = 25
print("Name: %s, Age: %d" % (name, age))
Output #
Name: John, Age: 25
Explanation #
- Multiple values are passed as a tuple.
%sreceives the string.%dreceives the integer.- Each placeholder is replaced in order.
Example 6: User Input #
main.py
name = input("Enter your name: ")
print("Welcome, %s!" % name)
Sample Input #
Alice
Output #
Welcome, Alice!
Explanation #
- The user enters a string.
%sinserts the entered name into the message.- The formatted greeting is displayed.
Example 7: Printing a Percent Sign #
main.py
score = 95
print("Score: %d%%" % score)
Output #
Score: 95%
Explanation #
%%prints a literal percent sign.%dformats the integer.- Without
%%, Python would interpret%as another format specifier.
Example 8: Formatting a Character #
main.py
letter = 'A'
print("Letter: %c" % letter)
Output #
Letter: A
Explanation #
%cformats a single character.- The character replaces the placeholder.
- The formatted string is printed.
Example 9: Mixing Different Data Types #
main.py
name = "Laptop"
quantity = 3
price = 599.99
print("Product: %s, Quantity: %d, Price: $%.2f" % (name, quantity, price))
Output #
Product: Laptop, Quantity: 3, Price: $599.99
Explanation #
%sformats the product name.%dformats the quantity.%.2fformats the price with two decimal places.- All placeholders are replaced in sequence.
Example 10: Checking the Result Type #
main.py
name = "Python"
result = "Welcome %s" % name
print(result)
print(type(result))
Output #
Welcome Python
<class 'str'>
Explanation #
- String formatting creates a new string.
- The formatted result is stored in
result. - Its data type is
str.
Common Mistakes #
1. Using the Wrong Format Specifier #
Incorrect
age = "21"
print("Age: %d" % age)
Output #
TypeError: %d format: a real number is required, not str
Reason
%d expects an integer, but a string was provided.
Correct
age = 21
print("Age: %d" % age)
or
age = "21"
print("Age: %s" % age)
2. Forgetting Parentheses for Multiple Values #
Incorrect
name = "John"
age = 25
print("Name: %s Age: %d" % name, age)
Output #
TypeError
Reason
Multiple values must be grouped into a tuple.
Correct
print("Name: %s Age: %d" % (name, age))
3. Forgetting to Escape the Percent Sign #
Incorrect
score = 80
print("Score: %d%" % score)
Output #
ValueError: incomplete format
Reason
A single % starts another format specifier.
Correct
print("Score: %d%%" % score)
4. Expecting %f to Show Only Two Decimal Places #
Incorrect
price = 19.5
print("Price: %f" % price)
Incorrect Expectation #
Price: 19.50
Actual Output #
Price: 19.500000
Reason
%f displays six decimal places by default.
Correct
print("Price: %.2f" % price)
Best Practices #
- Use the correct format specifier for each data type.
- Use
%.2fwhen displaying floating-point values with two decimal places. - Group multiple values into a tuple.
- Use
%%to print a percent sign. - Prefer f-strings for new Python programs, but understand
%formatting for maintaining older code.
Key Points to Remember #
%formatting is known as printf-style formatting.%sformats strings.%dformats integers.%fformats floating-point numbers.%.2flimits floating-point output to two decimal places.- Multiple values are passed as a tuple.
%formatting creates and returns a new string.