↵
1. Old-Style String Formatting↵
Old-style formatting uses the % operator to format strings. It's a carryover from C's printf function and is less preferred in modern Python code. However, you may still encounter it in older codebases.↵
↵
Here's a basic example:↵
↵
python↵
Copy code↵
name = "Alice"↵
age = 30↵
formatted_string = "Name: %s, Age: %d" % (name, age)↵
print(formatted_string)↵
In this example:↵
↵
%s is a placeholder for a string.↵
%d is a placeholder for a decimal integer.↵
The % operator is used to inject values into the string.↵
2. The .format() Method↵
Introduced in Python 2.6, the .format() method provides more flexibility and readability compared to old-style formatting. It allows for more precise control over how variables are inserted into strings.↵
↵
Here's how you would use it:↵
↵
python↵
Copy code↵
name = "Bob"↵
age = 25↵
formatted_string = "Name: {}, Age: {}".format(name, age)↵
print(formatted_string)↵
In this example:↵
↵
{} serves as a placeholder.↵
.format() is called on the string object.↵
Inside the format() method, you provide the variables in the order you want them inserted.↵
You can also specify the index of the arguments:↵
↵
python↵
Copy code↵
formatted_string = "Name: {1}, Age: {0}".format(age, name)↵
print(formatted_string)↵
3. f-strings (Python 3.6+)↵
f-strings provide a more concise and readable way to format strings. They allow you to embed expressions inside string literals, using curly braces {} to evaluate variables or expressions within a string.↵
↵
Here's an example:↵
↵
python↵
Copy code↵
name = "Charlie"↵
age = 35↵
formatted_string = f"Name: {name}, Age: {age}"↵
print(formatted_string)↵
In this example:↵
↵
The f prefix before the string indicates that it's an f-string.↵
Variables are directly placed inside the curly braces, allowing for clear and concise string interpolation.↵
F-strings are generally preferred for their simplicity and readability. They also offer the most concise syntax, especially when dealing with complex expressions or multiple variables in a single string.↵
↵
Additional Formatting Options↵
Specifying Formatting↵
You can also specify formatting within the placeholders to control how the values are displayed. For example:↵
↵
python↵
Copy code↵
pi = 3.14159↵
formatted_pi = "Pi value: {:.2f}".format(pi)↵
print(formatted_pi)↵
In this example, :.2f specifies that pi should be formatted as a floating-point number with 2 decimal places.↵
↵
Formatting with Dictionary↵
When working with dictionaries, you can use dictionary unpacking with f-strings:↵
↵
python↵
Copy code↵
person = {'name': 'David', 'age': 28}↵
formatted_string = f"Name: {person['name']}, Age: {person['age']}"↵
print(formatted_string)↵
These are some of the common methods and options for string formatting in Python. Choosing the right method often depends on the Python version you are using and personal preference, with f-strings being the most modern and recommended approach for Python 3.6 and above.↵
↵
↵
↵
↵