Python Strings : Format Strings
In Python, you can format strings in various ways to create well-structured and readable output. Python offers several methods to achieve string formatting. Here are the primary techniques:
1. Using format() Method
The format() method allows you to insert values into placeholders in a string.
name = "John"
age = 30
result = "My name is {} and I am {} years old.".format(name, age)
print(result) # Output: "My name is John and I am 30 years old."
You can specify the positions of the values:
result = "My name is {1} and I am {0} years old.".format(age, name)
print(result) # Output: "My name is John and I am 30 years old."
2. Using f-Strings (Formatted String Literals)
Introduced in Python 3.6, f-strings provide a concise way to embed expressions inside string literals.
name = "John"
age = 30
result = f"My name is {name} and I am {age} years old."
print(result) # Output: "My name is John and I am 30 years old."
You can also use expressions inside f-strings:
result = f"I will be {age + 5} years old in 5 years."
print(result) # Output: "I will be 35 years old in 5 years."
3. Using % Operator
This is an older method of formatting strings using the % operator. It’s similar to printf-style formatting in languages like C.
name = "John"
age = 30
result = "My name is %s and I am %d years old." % (name, age)
print(result) # Output: "My name is John and I am 30 years old."
4. Named Placeholders in format()
You can give names to the placeholders in the format() method and pass values by name.
result = "My name is {name} and I am {age} years old.".format(name="John", age=30)
print(result) # Output: "My name is John and I am 30 years old."
5. Formatting Numbers with format()
You can format numbers, such as floating-point values, with the format() method or f-strings.
pi = 3.14159265358979
result = "The value of pi is {:.2f}".format(pi) # Rounds to 2 decimal places
print(result) # Output: "The value of pi is 3.14"
With f-strings:
result = f"The value of pi is {pi:.2f}"
print(result) # Output: "The value of pi is 3.14"
6. Padding and Aligning Strings
You can align and pad strings to a specific width using format() or f-strings.
- Left Align (
<), Right Align (>), and Center Align (^):
result = "{:<10} is left aligned.".format("text")
print(result) # Output: "text is left aligned."
result = "{:>10} is right aligned.".format("text")
print(result) # Output: " text is right aligned."
result = "{:^10} is center aligned.".format("text")
print(result) # Output: " text is center aligned."
With f-strings:
result = f"{'text':<10} is left aligned."
print(result) # Output: "text is left aligned."
7. Formatting with Dictionary Keys
You can use dictionary keys for placeholders when using the format() method.
person = {'name': 'John', 'age': 30}
result = "My name is {name} and I am {age} years old.".format(**person)
print(result) # Output: "My name is John and I am 30 years old."
8. Formatting with Comma Separators
You can format numbers with commas as thousands separators.
number = 1234567890
result = "{:,}".format(number)
print(result) # Output: "1,234,567,890"
With f-strings:
result = f"{number:,}"
print(result) # Output: "1,234,567,890"
9. Binary, Hex, and Octal Formatting
You can format integers as binary, hexadecimal, or octal using format() or f-strings.
number = 255
result = "Binary: {0:b}, Hex: {0:x}, Octal: {0:o}".format(number)
print(result) # Output: "Binary: 11111111, Hex: ff, Octal: 377"
With f-strings:
result = f"Binary: {number:b}, Hex: {number:x}, Octal: {number:o}"
print(result) # Output: "Binary: 11111111, Hex: ff, Octal: 377"
Summary of Common Formatting Options
{}: Basic placeholder.{:<10}: Left-align to 10 spaces.{:>10}: Right-align to 10 spaces.{:^10}: Center-align to 10 spaces.{:.2f}: Format a floating-point number with 2 decimal places.{:,}: Add commas as thousand separators.{0:b}: Binary format.{0:x}: Hexadecimal format.
Each method can be used based on the need for readability, flexibility, or code compatibility.