Skip to content
Related Articles

Related Articles

Python | Optional padding in list elements

Improve Article
Save Article
  • Last Updated : 24 Nov, 2022
Improve Article
Save Article

In real world problems, we sometimes require to pad the element of list according to a condition that maximum characters have reached. Padding a number with 0 if it’s length is less than required by any field is one of the basic issues that occur in web forms in Web Development. Let’s discuss certain ways in which this issue can be solved. 
Method #1 : Using list comprehension This problem can be solved easily using the basic list comprehension in which we just need to use string formatting to perform the optional padding with 0 if size of each element is less than the specified size. 

Python3




# Python3 code to demonstrate
# to perform list element padding
# using list comprehension
 
# initializing list
test_list = [3, 54, 4, 1, 10]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using list comprehension
# to perform list element padding
res = ["%02d" % i for i in test_list]
 
# printing result
print("The list after element padding " + str(res))

Output

The original list is : [3, 54, 4, 1, 10]
The list after element padding ['03', '54', '04', '01', '10']

  Method #2 : Using str.rjust() There is a function dedicated in python to do this job. rjust() function does the task of specifying the size of the string and also takes the character in which the character has to be padded. 

Python3




# Python3 code to demonstrate
# to perform list element padding
# using str.rjust()
 
# initializing list
test_list = [3, 54, 4, 1, 10]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using str.rjust()
# to perform list element padding
res = [str(i).rjust(2, '0') for i in test_list]
 
# printing result
print("The list after element padding " + str(res))

Output

The original list is : [3, 54, 4, 1, 10]
The list after element padding ['03', '54', '04', '01', '10']

Method #3 : Using max() , len() and str() methods

Python3




# Python3 code to demonstrate
# to perform list element padding
 
# initializing list
test_list = [3, 54, 4, 1, 10]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using list comprehension
# to perform list element padding
a = max(test_list)
b = len(str(a))
res = []
for i in test_list:
    c = len(str(i))
    if(c != b):
        x = "0"*(b-c)+str(i)
        res.append(x)
    else:
        res.append(str(i))
# printing result
print("The list after element padding " + str(res))

Output

The original list is : [3, 54, 4, 1, 10]
The list after element padding ['03', '54', '04', '01', '10']

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!