String formatting is a fundamental skill in Python that allows you to create dynamic and readable strings. Python offers several methods for formatting strings, each with its own strengths and use cases. In this tutorial, we'll cover three primary methods: the `%` operator, the `str.format()` method, and f-strings. ### Using the `%` Operator for String Formatting The `%` operator is an older method of formatting strings, but it is still widely used in many codebases.
# Define variables name = "Alice" age = 25 # Use the % operator for string formatting formatted_string = "Hello, %s. You are %d years old." % (name, age) print(formatted_string)
Hello, Alice. You are 25 years old.
In this example, `%s` is a placeholder for a string, and `%d` is a placeholder for an integer. The values in the tuple following the `%` operator replace these placeholders in the string. ### Using the `str.format()` Method The `str.format()` method is a more modern way of formatting strings and offers greater flexibility and readability.
# Define variables name = "Bob" age = 30 # Use the str.format() method for string formatting formatted_string = "Hello, {}. You are {} years old.".format(name, age) print(formatted_string)
Hello, Bob. You are 30 years old.
In this snippet, `{}` are placeholders that will be replaced by the arguments passed to the `format()` method. #### Named Placeholders You can also use named placeholders with the `str.format()` method.
# Define variables name = "Charlie" age = 35 # Use named placeholders with the str.format() method formatted_string = "Hello, {name}. You are {age} years old.".format(name=name, age=age) print(formatted_string)
Hello, Charlie. You are 35 years old.
Named placeholders make it clear which values are being substituted, enhancing readability. ### Using F-Strings (Literal String Interpolation) F-strings, introduced in Python 3.6, are the most modern and efficient way to format strings. F-strings are prefixed with an `f` and use curly braces `{}` to evaluate expressions directly within the string.
# Define variables name = "Diana" age = 40 # Use f-strings for string formatting formatted_string = f"Hello, {name}. You are {age} years old." print(formatted_string)
Hello, Diana. You are 40 years old.
F-strings are not only concise but also faster than the other methods. #### Inline Expressions You can include expressions directly within the curly braces of f-strings.
# Define variables a = 5 b = 10 # Use expressions within f-strings formatted_string = f"The sum of {a} and {b} is {a + b}." print(formatted_string)
The sum of 5 and 10 is 15.
### Formatting Floats and Other Data Types All three methods allow you to format floats and other data types with specific formatting options. #### Formatting Floats
# Define a float variable pi = 3.14159 # Using the % operator formatted_string = "Pi approximately equals %.2f" % pi print(formatted_string) # Using the str.format() method formatted_string = "Pi approximately equals {:.2f}".format(pi) print(formatted_string) # Using f-strings formatted_string = f"Pi approximately equals {pi:.2f}" print(formatted_string)
Pi approximately equals 3.14 Pi approximately equals 3.14 Pi approximately equals 3.14
In each method, `:.2f` ensures that the float is formatted to two decimal places. #### Padding and Alignment You can control padding and alignment with all three methods.
# Define a list of names names = ["Alice", "Bob", "Charlie"] # Using the % operator for name in names: print("%-10s" % name) # Left-aligned with padding # Using the str.format() method for name in names: print("{:<10}".format(name)) # Left-aligned with padding # Using f-strings for name in names: print(f"{name:<10}") # Left-aligned with padding
Alice Bob Charlie Alice Bob Charlie Alice Bob Charlie
In each method, `-10s`, `<10`, and `<10` ensure left-alignment with a total width of 10 characters. ### Combining Multiple Formatting Options You can combine multiple formatting options to create complex formatted strings.
# Define variables name = "Emily" balance = 1234.567 # Using the % operator formatted_string = "Name: %-10s | Balance: $%8.2f" % (name, balance) print(formatted_string) # Using the str.format() method formatted_string = "Name: {:<10} | Balance: ${:8.2f}".format(name, balance) print(formatted_string) # Using f-strings formatted_string = f"Name: {name:<10} | Balance: ${balance:8.2f}" print(formatted_string)
Name: Emily | Balance: $ 1234.57 Name: Emily | Balance: $ 1234.57 Name: Emily | Balance: $ 1234.57
In this example, we format the name with left-alignment and padding, and the balance with right-alignment, width, and two decimal places.