Python String Formatting
Introduction
String formatting is a fundamental skill in Python programming that allows you to create dynamic and readable text output.
This tutorial covers the main methods of string formatting in Python, helping you understand when and how to use each technique effectively.
Readability counts.
Overview of String Formatting Methods
Python offers multiple ways to format strings, each with its own syntax and use cases.
The three primary methods are the % operator, the str.format() method, and f-strings introduced in Python 3.6.
- Percent (%) formatting: An older style using placeholders like %s and %d.
- str.format() method: More powerful and flexible, using curly braces {} as placeholders.
- F-strings: The newest and most readable method, allowing expressions inside string literals.
Percent (%) Formatting
Percent formatting uses placeholders in the string that are replaced by values after the % operator.
Common placeholders include %s for strings, %d for integers, and %f for floating-point numbers.
- Syntax example: 'Hello, %s!' % name
- Supports tuple for multiple values: 'Name: %s, Age: %d' % (name, age)
- Limited flexibility compared to newer methods
The str.format() Method
The str.format() method uses curly braces {} as placeholders and allows positional and keyword arguments.
It supports advanced formatting options like padding, alignment, and number formatting.
- Basic usage: 'Hello, {}'.format(name)
- Positional arguments: '{0} {1}'.format(first, second)
- Keyword arguments: '{name} is {age} years old'.format(name='Alice', age=30)
- Format specifiers: '{:.2f}'.format(3.14159) formats float to 2 decimal places
F-Strings (Formatted String Literals)
F-strings provide a concise and readable way to embed expressions inside string literals using curly braces.
They are prefixed with the letter 'f' and evaluated at runtime.
- Example: f'Hello, {name}!'
- Supports any valid Python expression inside braces: f'{value * 2}'
- Allows inline formatting: f'{pi:.3f}' formats pi to 3 decimal places
- Recommended for Python 3.6 and above due to clarity and performance
Comparison of String Formatting Methods
Choosing the right string formatting method depends on your Python version and readability preferences.
| Method | Introduced | Syntax Example | Key Features | Recommended Use |
|---|---|---|---|---|
| Percent (%) | Python 2 | 'Hello, %s!' % name | Simple placeholders, limited flexibility | Legacy code |
| str.format() | Python 2.6 | 'Hello, {}'.format(name) | Flexible, supports advanced formatting | General use |
| F-strings | Python 3.6 | f'Hello, {name}!' | Concise, readable, supports expressions | Modern Python code |
Examples
name = 'Alice'
age = 30
print('Name: %s, Age: %d' % (name, age))This example uses %s and %d placeholders to format a string with a name and age.
name = 'Bob'
pi = 3.14159
print('Hello, {}. Pi rounded: {:.2f}'.format(name, pi))This example formats a string with positional arguments and rounds pi to 2 decimal places.
name = 'Carol'
value = 7
print(f'Hello, {name}. Double value: {value * 2}')This example uses an f-string to embed variables and expressions directly inside the string.
Best Practices
- Prefer f-strings for Python 3.6+ for readability and performance.
- Use str.format() when compatibility with Python versions before 3.6 is required.
- Avoid percent (%) formatting in new code as it is less flexible and harder to read.
- Use format specifiers to control number formatting and alignment for clean output.
- Keep formatting expressions simple to maintain readability.
Common Mistakes
- Mixing different formatting methods in the same string.
- Forgetting to pass a tuple when using multiple values with % formatting.
- Using complex expressions inside f-strings that reduce readability.
- Not specifying format specifiers leading to inconsistent output.
- Using outdated % formatting in modern Python projects.
Hands-on Exercise
Format User Information
Write a Python script that takes a user's name, age, and height, then prints a formatted string using f-strings.
Expected output: Hello, Alice. You are 30 years old and 5.75 feet tall.
Hint: Use f-strings and format the height to two decimal places.
Convert Percent Formatting to str.format()
Given a string using percent (%) formatting, rewrite it using the str.format() method.
Expected output: Formatted string using str.format() with the same output as the original.
Hint: Replace %s and %d placeholders with {} and pass arguments to format().
Interview Questions
What are the main string formatting methods in Python?
InterviewThe main methods are percent (%) formatting, the str.format() method, and f-strings.
Why are f-strings recommended over other formatting methods?
InterviewF-strings are more readable, concise, and efficient, allowing expressions inside string literals and were introduced in Python 3.6.
How do you format a floating-point number to two decimal places using str.format()?
InterviewUse a format specifier like {:.2f} inside the curly braces, for example: '{:.2f}'.format(3.14159).
Summary
Python provides multiple ways to format strings, each suited for different scenarios and Python versions.
Percent (%) formatting is older and less flexible, while str.format() offers more control and is widely used.
F-strings are the modern, preferred method for Python 3.6 and above due to their readability and power.
Understanding these methods helps you write clear and maintainable Python code.
FAQ
Which string formatting method is fastest in Python?
F-strings are generally the fastest because they are evaluated at runtime and optimized by the interpreter.
Can I use expressions inside f-strings?
Yes, f-strings allow any valid Python expression inside the curly braces.
Are f-strings available in Python 2?
No, f-strings were introduced in Python 3.6 and are not available in Python 2.
