Welcome to The Coding College, your trusted resource for mastering Python! In this guide, we’ll explore Python String Formatting, a powerful tool for creating dynamic, readable, and well-structured strings in Python.
String formatting allows you to embed variables or values into strings, making your programs more user-friendly and efficient. Let’s dive in!
What is String Formatting in Python?
String formatting is the process of injecting variables or expressions into strings. Python provides several ways to format strings:
- Old-style (
%
) formatting. str.format()
method.- f-strings (formatted string literals).
Each method has unique features and use cases, and we’ll cover all of them.
1. Old-Style (%
) Formatting
This is the legacy way of formatting strings. You use placeholders, such as %s
for strings and %d
for integers.
Example
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
Output
My name is Alice and I am 25 years old.
Placeholders
%s
: String%d
: Integer%f
: Float (default precision: 6 decimal places)
Formatting Floats
pi = 3.1415926535
print("The value of pi is %.2f." % pi) # Limits to 2 decimal places
Output:
The value of pi is 3.14.
2. The str.format()
Method
The str.format()
method offers more flexibility than %
formatting.
Basic Example
name = "Bob"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
Positional and Keyword Arguments
- Positional:
print("The order is {0}, {1}, and {2}.".format("apple", "banana", "cherry"))
Output:
The order is apple, banana, and cherry.
- Keyword:
print("The coordinates are x={x}, y={y}.".format(x=5, y=10))
Output:
The coordinates are x=5, y=10.
Formatting Numbers
You can format numbers for padding, alignment, or precision:
print("Value: {:.2f}".format(3.14159)) # Rounds to 2 decimal places
print("Padded: {:05d}".format(42)) # Pads with zeroes to make it 5 digits
Output:
Value: 3.14
Padded: 00042
3. F-Strings (Formatted String Literals)
Introduced in Python 3.6, f-strings are the most concise and modern way to format strings. Use an f
prefix before the string and embed variables inside curly braces {}
.
Basic Example
name = "Eve"
age = 22
print(f"My name is {name} and I am {age} years old.")
Inline Expressions
F-strings allow you to embed expressions directly.
print(f"The sum of 5 and 3 is {5 + 3}.")
Output:
The sum of 5 and 3 is 8.
Formatting Numbers
pi = 3.14159
print(f"Pi to 2 decimal places: {pi:.2f}")
Output:
Pi to 2 decimal places: 3.14
Comparing String Formatting Methods
Method | Pros | Cons |
---|---|---|
% formatting | Simple for basic use cases. | Limited functionality, less readable. |
str.format() | Flexible, supports advanced use. | Verbose for simple tasks. |
f-strings | Concise, efficient, and readable. | Requires Python 3.6 or later. |
Exercises to Practice Python String Formatting
Exercise 1: Greeting Message
Write a program that asks for the user’s name and age, then formats and displays a greeting using f-strings.
Exercise 2: Temperature Conversion
Create a program that takes a temperature in Celsius, converts it to Fahrenheit, and displays the result using the str.format()
method.
Exercise 3: Table Formatter
Write a program to print a neatly formatted table of data using str.format()
or f-strings.
Why Learn Python String Formatting with The Coding College?
At The Coding College, we focus on practical, real-world Python applications. Mastering string formatting will empower you to create clean, professional output in your Python programs.
Conclusion
Python’s string formatting options provide the flexibility and power to create dynamic and well-structured strings. Whether you’re using %
formatting, str.format()
, or the modern f-strings, each method has its place in your programming toolkit.