Reputation: 77
I have a list like so obtained after some mathematic operations:
[[899, 6237], [898, 6237], [897, 6237],
[896, 6237], [895, 6237], [899, 6238],
[898, 6238], [897, 6238], [896, 6238],
[895, 6238], [899, 6239], [898, 6239],
[897, 6239], [896, 6239], [895, 6239],
[899, 6240], [898, 6240], [897, 6240],
[896, 6240], [895, 6240]]
I would like the components of each sublist become string of 4 characters size. This is a example of what I want with the first element of the main list:
['0899','6237']
Upvotes: -1
Views: 52
Reputation: 6589
You can use a simple list comprehension
new_list = [['0' + str(i[0]), str(i[1])] for i in original_list]
new_list
output:
[['0899', '6237'], ['0898', '6237'], ['0897', '6237'], ['0896', '6237'], ['0895', '6237'], ['0899', '6238'], ['0898', '6238'], ['0897', '6238'], ['0896', '6238'], ['0895', '6238'], ['0899', '6239'], ['0898', '6239'], ['0897', '6239'], ['0896', '6239'], ['0895', '6239'], ['0899', '6240'], ['0898', '6240'], ['0897', '6240'], ['0896', '6240'], ['0895', '6240']]
Upvotes: 1
Reputation: 3607
The correct way is to use format(), although the zfill is also pretty sweet. Here is a much uglier solution that no one should ever use:
list = [
[899, 6237], [898, 6237], [897, 6237], [896, 6237], [895, 6237], [899, 6238],
[898, 6238], [897, 6238], [896, 6238], [895, 6238], [899, 6239], [898, 6239],
[897, 6239], [896, 6239], [895, 6239], [899, 6240], [898, 6240], [897, 6240],
[896, 6240], [895, 6240]
]
def yolo(pair):
pair = map(str,pair)
return ['0'*(4-len(pair[0])) + pair[0], pair[1]]
list = map(yolo,list)
Upvotes: 1
Reputation: 11134
You can use zfill with list comprehension:
list_name = [[str(i).zfill(4) for i in element] for element in your_list]
Demo:
>>>str(890).zfill(4)
'0890'
>>>str(890).zfill(5)
'00890'
Upvotes: 1
Reputation: 368964
Using list comprehension and format
:
>>> lst = [
... [899, 6237], [898, 6237], [897, 6237], [896, 6237], [895, 6237],
... [899, 6238], [898, 6238], [897, 6238], [896, 6238], [895, 6238],
... [899, 6239], [898, 6239], [897, 6239], [896, 6239], [895, 6239],
... [899, 6240], [898, 6240], [897, 6240], [896, 6240], [895, 6240],
... ]
>>> [[format(a, '04'), format(b, '04')] for a, b in lst]
[['0899', '6237'], ['0898', '6237'], ['0897', '6237'], ['0896', '6237'],
['0895', '6237'], ['0899', '6238'], ['0898', '6238'], ['0897', '6238'],
['0896', '6238'], ['0895', '6238'], ['0899', '6239'], ['0898', '6239'],
['0897', '6239'], ['0896', '6239'], ['0895', '6239'], ['0899', '6240'],
['0898', '6240'], ['0897', '6240'], ['0896', '6240'], ['0895', '6240']]
You can also use str.format
:
>>> '{:04}'.format(899)
'0899'
or %
-operator (printf
-style formatting):
>>> '%04d' % 899
'0899'
Upvotes: 2