I frequently find myself with a list that looks like this:
lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
What is the most pythonic way to convert specific strings in this list to ints?
I typically do something like this:
lst = [lst[0], int(lst[1]), int(lst[2]), lst[3], ...]
The above approach seems wrong. Are there better way to convert only certain items in lists to integers?
To convert a list of strings to a list of integers: Pass the int() class and the list to the map() function. The map() function will pass each item of the list to the int() class. The new list will only contain integer values.
To do this we use the split() method in string. The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.
Another approach to convert a list of multiple integers into a single integer is to use map() function of Python with str function to convert the Integer list to string list. After this, join them on the empty string and then cast back to integer.
I would say something like:
>>> lst = ['A', '1', '2', 'B', '1', 'C', 'D', '4', '1', '4', '5', 'Z', 'D']
>>> lst = [int(s) if s.isdigit() else s for s in lst]
>>> lst
['A', 1, 2, 'B', 1, 'C', 'D', 4, 1, 4, 5, 'Z', 'D']
int
and .isdigit
can disagree in Unicode case i.e., int
might fail to parse a string even if .isdigit
returns True
for the string.
def maybe_int(s):
try:
return int(s)
except ValueError:
return s
lst = [maybe_int(s) for s in lst]
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