Python - Custom space size padding in Strings List

When working with string lists in Python, you may need to add custom spacing around each string element. This can be achieved using string concatenation with multiplied spaces or built-in string methods like center().

Method 1: Using String Concatenation

You can add custom leading and trailing spaces by multiplying space characters and concatenating them ?

my_list = ["Python", "is", "great"]

print("The list is:")
print(my_list)

lead_size = 3
trail_size = 2

my_result = []
for elem in my_list:
   my_result.append((lead_size * ' ') + elem + (trail_size * ' '))

print("The result is:")
print(my_result)
The list is:
['Python', 'is', 'great']
The result is:
['   Python  ', '   is  ', '   great  ']

Method 2: Using List Comprehension

A more concise approach using list comprehension ?

my_list = ["Python", "is", "great"]
lead_size = 3
trail_size = 2

my_result = [(lead_size * ' ') + elem + (trail_size * ' ') for elem in my_list]

print("Original list:", my_list)
print("Padded list:", my_result)
Original list: ['Python', 'is', 'great']
Padded list: ['   Python  ', '   is  ', '   great  ']

Method 3: Using center() for Equal Padding

For equal padding on both sides, use the center() method ?

my_list = ["Python", "is", "great"]
total_width = 10

my_result = [elem.center(total_width) for elem in my_list]

print("Original list:", my_list)
print("Centered list:", my_result)
Original list: ['Python', 'is', 'great']
Centered list: ['  Python  ', '    is    ', '  great   ']

Comparison

Method Flexibility Best For
String Concatenation High (custom leading/trailing) Different padding sizes
List Comprehension High (custom leading/trailing) Concise code
center() Medium (equal padding) Uniform formatting

Conclusion

Use string concatenation with multiplied spaces for custom leading and trailing padding. For equal padding, center() provides a clean solution. List comprehension offers the most concise syntax for simple transformations.

Updated on: 2026-03-26T02:04:12+05:30

431 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements