String Formatting
String formatting allows you to create strings with embedded values in a controlled and readable manner. Python offers several methods for string formatting:
1. Old-style String Formatting (using %)
This method is older but still supported:
Python
name = "Alice"age = 30formatted_string = "Hello, %s! You are %d years old." % (name, age)print(formatted_string) # Output: Hello, Alice! You are 30 years old.·
%s is a placeholder for a
string.
·
%d is a placeholder for an
integer.
·
The % operator is used to
substitute values into the string.
2. Format Method (.format())
This method is more versatile and readable:
Python
name = "Bob"price = 9.99formatted_string = "Hello, {}! The price is {:.2f}".format(name, price)print(formatted_string) # Output: Hello, Bob! The price is 9.99·
{} are placeholders for
values.
·
.2f specifies a floating-point
number with two decimal places.
3. f-strings (Formatted String Literals)
Introduced in Python 3.6, f-strings provide a cleaner and more concise way to format strings:
Python
name = "Charlie"item = "apple"quantity = 5formatted_string = f"Hello, {name}! You bought {quantity} {item}s."print(formatted_string) # Output: Hello, Charlie! You bought 5 apples.·
f before the string indicates
an f-string.
·
Expressions within curly braces {} are evaluated and inserted
into the string.
Key Points
· Choose the method that best suits your needs based on readability and complexity.
· f-strings are generally preferred for their simplicity and efficiency.
·
Use format specifiers (e.g., :.2f) for precise formatting of
numbers.