Does anyone knows what magic I have to use to change x list:
x = [1,2,3,4,5,11]
into y list?
y = ['01','02','03','04','05','11']
Thank you all in advance for helping me...
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Python provides a nicer way to do this kind of task by using the map() built-in function. The map() function iterates over all elements in a list (or a tuple), applies a function to each and returns a new iterator of the new elements.
Python map() function map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) Parameters : fun : It is a function to which map passes each element of given iterable. iter : It is a iterable which is to be mapped.
Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.
You can use a list comprehension (Python 2.6+):
y = ["{0:0>2}".format(v) for v in x]
Or for Python prior to 2.6:
y = ["%02d" % v for v in x]
Or for Python 3.6+ using f-strings:
y = [f'{v:02}' for v in x]
Edit: Missed the fact that you wanted zero-padding...
You want to use the built-in map
function:
>>> x = [1,2,3,4,5]
>>> x
[1, 2, 3, 4, 5]
>>> y = map(str, x)
>>> y
['1', '2', '3', '4', '5']
EDIT You changed the requirements on me! To make it display leading zeros, you do this:
>>> x = [1,2,3,4,5,11]
>>> y = ["%02d" % v for v in x]
>>> y
['01', '02', '03', '04', '05', '11']
I would use a list comprehension myself, but here is another solution using map for those interested...
map(lambda v: "%02d" %v, x)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With