Common string formatting operations in Python, with examples and outputs:
- f-Strings (Python 3.6+)
- str.format() method
- Old-style % formatting
- String methods for formatting
- Advanced formatting techniques
1. f-Strings (Python 3.6+)
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 30 years old.
# Expressions inside f-strings
print(f"The square of 7 is {7**2}")
# Output: The square of 7 is 49
# Formatting decimal places
pi = 3.14159
print(f"Pi to 2 decimal places: {pi:.2f}")
# Output: Pi to 2 decimal places: 3.14
2. str.format() Method
# Basic formatting
print("My name is {} and I am {} years old.".format("Bob", 25))
# Output: My name is Bob and I am 25 years old.
# Using positional arguments
print("The {0} jumped over the {1}".format("cow", "moon"))
# Output: The cow jumped over the moon
# Using keyword arguments
print("The {animal} jumped over the {object}".format(animal="cow", object="moon"))
# Output: The cow jumped over the moon
# Alignment and padding
print("|{:<10}|{:>10}|{:^10}|".format("left", "right", "center"))
# Output: |left | right| center |
3. Old-style % Formatting (still supported, but not recommended for new code)
name = "Charlie"
age = 35
print("My name is %s and I am %d years old." % (name, age))
# Output: My name is Charlie and I am 35 years old.
# Formatting floats
price = 19.99
print("The price is $%.2f" % price)
# Output: The price is $19.99
4. String Methods for Formatting
# Capitalizing
text = "hello, world!"
print(text.capitalize())
# Output: Hello, world!
# Title case
print(text.title())
# Output: Hello, World!
# Upper and lower case
print(text.upper())
# Output: HELLO, WORLD!
print(text.lower())
# Output: hello, world!
# Centering text
print(text.center(20, '*'))
# Output: ***hello, world!****
# Removing whitespace
spacey_text = " trim me "
print(spacey_text.strip())
# Output: trim me
5. Advanced Formatting
# Formatting numbers with comma as thousand separator
large_num = 1234567.89
print(f"{large_num:,.2f}")
# Output: 1,234,567.89
# Percentage formatting
percentage = 0.8523
print(f"{percentage:.2%}")
# Output: 85.23%
# Formatting dates (requires importing datetime)
from datetime import datetime
now = datetime.now()
print(f"Current date: {now:%Y-%m-%d}")
# Output: Current date: 2024-07-04
# Hexadecimal and binary formatting
number = 42
print(f"Hex: {number:x}, Binary: {number:b}")
# Output: Hex: 2a, Binary: 101010
# Using format spec mini-language for complex formatting
for align, text in zip('<^>', ['left', 'center', 'right']):
print(f'{text:{align}10}')
# Output:
# left
# center
# right