Python - Custom space size padding in Strings List


When it is required to customize the space size padding in a list of strings, an empty list, an iteration and the ‘append’ method is used.

Example

Below is a demonstration of the same

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)

Output

The list is :
['Python', 'is', 'great']
The result is :
[' Python ', ' is ', ' great ']

Explanation

  • A list is defined and is displayed on the console.

  • The lead and trail sizes are defined.

  • An empty list is defined.

  • The original list is iterated over, and the lead size and trail sizes are multiplied with empty spaces.

  • This is appended to the result.

  • This is the output that is displayed on the console.

Updated on: 15-Sep-2021

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements