String Formatting Deep Dive

Python StringsFree Lesson

Advertisement

String Formatting Deep Dive

f-strings, .format(), % formatting, templates, and advanced formatting techniques.

Overview

Multiple ways to format strings in Python.

f-Strings (Recommended)

name = "Alice"
age = 25
pi = 3.14159

# Basic interpolation
print(f"Hello, {name}!")  # Hello, Alice!
print(f"Age: {age}")  # Age: 25

# Expressions
print(f"Next year: {age + 1}")  # Next year: 26
print(f"Name uppercase: {name.upper()}")  # Name uppercase: ALICE

# Formatting numbers
print(f"Pi: {pi:.2f}")  # Pi: 3.14
print(f"Pi: {pi:.4f}")  # Pi: 3.1416

# Thousand separators
population = 1234567890
print(f"Population: {population:,}")  # Population: 1,234,567,890

# Percentage
success_rate = 0.8567
print(f"Success: {success_rate:.1%}")  # Success: 85.7%

# Padding and alignment
for i in range(1, 6):
    print(f"Item {i:2d}: {'*' * i}")

# Output:
# Item  1: *
# Item  2: **
# Item  3: ***
# Item  4: ****
# Item  5: *****

# Width and alignment
names = ["Alice", "Bob", "Charlie"]
for name in names:
    print(f"{name:>10} | {len(name):^5} | {'hello':<10}")

# Output:
#      Alice |   5   | hello      
#        Bob |   3   | hello      
#    Charlie |   7   | hello      

# Debugging with = sign
x = 10
y = 20
print(f"{x=}, {y=}, {x+y=}")  # x=10, y=20, x+y=30

# Nested f-strings
data = {"name": "Alice", "scores": [85, 92, 78]}
print(f"{'Name: ' + data['name']:^20}")
print(f"Average: {sum(data['scores'])/len(data['scores']):.1f}")

.format() Method

# Positional arguments
print("Hello, {}!".format("Alice"))  # Hello, Alice!
print("{} is {} years old".format("Alice", 25))

# Numbered arguments
print("{0} {1} {0}".format("hello", "world"))  # hello world hello

# Named arguments
print("{name} is {age}".format(name="Alice", age=25))

# Accessing attributes
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 25)
print("{0.name} is {0.age}".format(p))

# Accessing items
data = {"name": "Alice", "age": 25}
print("{0[name]} is {0[age]}".format(data))

# Format specifications
print("{:.2f}".format(3.14159))  # 3.14
print("{:>10}".format("hello"))  #      hello
print("{:<10}".format("hello"))  # hello     
print("{:^10}".format("hello"))  #   hello   
print("{:,}".format(1234567))  # 1,234,567
print("{:.2%}".format(0.8567))  # 85.67%

% Formatting (Old Style)

# Basic
print("Hello, %s!" % "Alice")  # Hello, Alice!
print("%s is %d years old" % ("Alice", 25))

# Multiple values
print("Name: %s, Age: %d, Score: %.2f" % ("Alice", 25, 85.5))

# Dictionary
data = {"name": "Alice", "age": 25}
print("%(name)s is %(age)d years old" % data)

# Padding
print("%10s" % "hello")  #      hello
print("%-10s" % "hello")  # hello     
print("%010d" % 42)  # 0000000042

Template Strings

from string import Template

# Basic template
t = Template("Hello, $name!")
print(t.substitute(name="Alice"))  # Hello, Alice!

# Safe substitution (missing keys ignored)
t = Template("$name is $age years old")
print(t.safe_substitute(name="Alice"))  # Alice is $age years old

# Delimiter customization
t = Template("$name${age}years")
print(t.substitute(name="Alice", age=25))  # Alice25years

Practice

Create a formatted report with aligned columns and numbers.

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement