python - Convert List of strings to ints without removing 0 -
so have list of strings want convert list of ints
['030', '031', '031', '031', '030', '031', '031', '032', '031', '032']
how should go new list not remove zeroes
i want this:
[030, 031, 031, 031, 030, 031, 031, 032, 031, 032]
not this:
[30, 31, 31, 31, 30, 31, 31, 32, 31, 32]
thanks
the value of int("030")
same value of int("30")
. leading 0
doesn't have semantic value when talking number - if want keep leading 0
, no longer storing number, rather representation of number, needs string.
the solution, if need use in both ways, store in commonly used form, , convert need it. if need leading 0 (that is, need string), keep is, , call int()
on values required.
if opposite true, can use string formatting number padded required number of digits:
>>> "{0:03d}".format(30) '030'
if 0 padding not consistent (that is, it's impossible recover formatting int
), might best keep in both forms:
>>> [(value, int(value)) value in values] [('030', 30), ('031', 31), ('031', 31), ('031', 31), ('030', 30), ('031', 31), ('031', 31), ('032', 32), ('031', 31), ('032', 32)]
what method best depends entirely on situation.
edit: specific case, in comments, want this:
>>> current = ("233", "199", "016") >>> modifier = "031" >>> ["".join(part) part in zip(*list(zip(*current))[:-1] + [modifier])] ['230', '193', '011']
to break down, want replace third digit of each number relevant number in modifier. done here using zip()
make columns of numbers - list(zip(*current))
gives [('2', '1', '0'), ('3', '9', '1'), ('3', '9', '6')]
- replace last column modified one, , use zip()
again give rows again. join individual digits strings.
note in 2.x, zip()
gives list, don't need wrap call in list()
. in 3.x, generator.
Comments
Post a Comment