Formatting containers using format() in Python

The format() method in Python provides powerful ways to control how containers like lists, tuples, dictionaries, and sets are displayed. This method allows you to customize alignment, padding, precision, and presentation of your data structures for better readability.

Formatting Lists

You can format lists by joining elements with custom separators using format() ?

my_list = [1, 2, 3, 4, 5]
formatted_list = ', '.join(['{}'.format(x) for x in my_list])
print(formatted_list)
1, 2, 3, 4, 5

The join() method combines the formatted numbers with a comma and space separator. Each integer value replaces the {} placeholder inside the format() method.

Formatting Tuples

Tuples work similarly to lists, even though they are immutable ?

my_tuple = ('apple', 'banana', 'orange')
formatted_tuple = ', '.join(['{}'.format(x) for x in my_tuple])
print(formatted_tuple)
apple, banana, orange

Formatting Dictionaries

Dictionaries can be formatted using named placeholders and the unpacking operator ?

my_dict = {'name': 'John', 'age': 33, 'city': 'Los Angeles'}
formatted_dict = 'Name: {name}, Age: {age}, City: {city}'.format(**my_dict)
print(formatted_dict)
Name: John, Age: 33, City: Los Angeles

The **my_dict syntax unpacks the dictionary, passing its contents as keyword arguments to the format() method.

Formatting Sets

Sets can be formatted using the same approach as lists ?

my_set = {1, 2, 3, 4, 5}
formatted_set = ', '.join(['{}'.format(x) for x in my_set])
print(formatted_set)
1, 2, 3, 4, 5

Formatting Class Objects

You can access object attributes directly in format strings ?

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

my_person = Person('John', 30)
formatted_person = 'Name: {p.name}, Age: {p.age}'.format(p=my_person)
print(formatted_person)
Name: John, Age: 30

Alignment and Padding

Use alignment specifiers to control text positioning: < (left), > (right), ^ (center) ?

my_list = ['apple', 'banana', 'orange']
for fruit in my_list:
    print('{:>10}'.format(fruit))
     apple
    banana
    orange

Precision Control

Control decimal places for floating-point numbers using precision specifiers ?

my_floats = [1.23456, 2.34567, 3.45678]
for num in my_floats:
    print('{:.2f}'.format(num))
1.23
2.35
3.46

Advanced Formatting Example

Combine multiple formatting options for complex layouts ?

my_dict = {'apple': 1.23, 'banana': 2.34, 'orange': 3.45}
for key, value in my_dict.items():
    print('{:<10}{:.2f}'.format(key, value))
apple     1.23
banana    2.34
orange    3.45

This creates a left-aligned column of fruit names (width 10) followed by prices formatted to 2 decimal places.

Conclusion

The format() method provides flexible container formatting with alignment, padding, and precision controls. Use it to create well-structured output for data analysis, reports, and user interfaces.

Updated on: 2026-03-27T01:18:46+05:30

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements