Python offers multiple techniques for formatting strings, each with unique advantages and use cases.
The traditional method of string formatting using %
operator:
name = "LabEx"
age = 5
print("My name is %s and I am %d years old" % (name, age))
A more flexible approach introduced in Python 3:
## Positional arguments
print("Hello, {} {}!".format("LabEx", "Platform"))
## Keyword arguments
print("Name: {name}, Age: {age}".format(name="Python", age=30))
The most modern and recommended approach in Python 3.6+:
name = "LabEx"
version = 2.0
print(f"Welcome to {name} version {version}")
Alignment and Padding
## Right-aligned with width
print(f"{'text':>10}") ## Right-aligned, 10 characters wide
## Left-aligned with width
print(f"{'text':<10}") ## Left-aligned, 10 characters wide
## Centered
print(f"{'text':^10}") ## Centered, 10 characters wide
## Floating point precision
pi = 3.14159
print(f"Pi: {pi:.2f}") ## Rounds to 2 decimal places
## Percentage formatting
percentage = 0.75
print(f"Completion: {percentage:.0%}") ## 75%
Technique |
Pros |
Cons |
%-Formatting |
Simple, legacy support |
Less readable, limited features |
.format() |
More flexible |
Verbose syntax |
f-Strings |
Most readable, performant |
Python 3.6+ only |
class Course:
def __init__(self, name, duration, difficulty):
self.name = name
self.duration = duration
self.difficulty = difficulty
def __str__(self):
return f"Course: {self.name}\nDuration: {self.duration} hours\nLevel: {self.difficulty}"
python_course = Course("Python Programming", 40, "Intermediate")
print(python_course)
Practical Use Cases
Logging and Reporting
def generate_report(total_users, active_users):
percentage = active_users / total_users * 100
return f"Total Users: {total_users}\nActive Users: {active_users}\nActivity Rate: {percentage:.2f}%"
print(generate_report(1000, 750))
Conclusion
Mastering string formatting is essential for creating readable and dynamic text in Python. LabEx recommends practicing these techniques to improve your programming skills.