Python | Construct N Range Equilength String list

Sometimes, while working with Python, we can have a problem in which we need to construct a string list which contains N range numbers. But we have requirement in which we need to keep each element of equal length. Let’s discuss certain ways in which this task can be performed.

Method #1: Using list comprehension + zfill()
The combination of above functionalities can be used to perform this task. In this, we perform the task of adding numbers using list comprehension and zfill() takes care of length required for each string.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Construct N Range Equilength String list
# using list comprehension + zfill()
  
# initialize N 
N = 6
  
# printing N 
print("Number of elements required : " + str(N))
  
# initialize K 
K = 3
  
# Construct N Range Equilength String list
# using list comprehension + zfill()
res = [str(ele).zfill(K) for ele in range(N)]
      
# printing result
print("K Length range strings list : " + str(res))

chevron_right


Output :



Number of elements required : 6
K Length range strings list : ['000', '001', '002', '003', '004', '005']

 

Method #2 : Using map() + string formatting
This task can also be performed using above functions. In this, we extend the logic of length using string formatting. And is used for constructing the N range.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Construct N Range Equilength String list
# using  map() + string formatting
  
# initialize N 
N = 6
  
# printing N 
print("Number of elements required : " + str(N))
  
# initialize K 
K = 3
  
# Construct N Range Equilength String list
# using  map() + string formatting
temp = '{:0' + str(K) + '}'
res = list(map(temp.format, range(N)))
      
# printing result
print("K Length range strings list : " + str(res))

chevron_right


Output :

Number of elements required : 6
K Length range strings list : ['000', '001', '002', '003', '004', '005']


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.