How can I convert a list of strings to a list of ints?
Let's say I have a string: line = "[1, 2, 12]\n"
and I want to convert it to a list of ints:[1, 2, 12]
I have a solution:
new_list = []
for char in line:
try:
new_list.append(int(char))
except ValueError:
pass
But this does not work for numbers with more than one digit. Is there a built-in / better way to do this? Thanks to
source to share
new_list = [int(num) for num in line.strip('[]\n').split(', ')]
A more readable solution would be:
line = line.strip('[]\n') list_of_strs = line.split(', ') list_of_nums = [] for elem in list_of_strs: list_of_nums.append(int(elem))
The first is line
devoid of the enclosed parentheses and newlines. Then the remaining line is split into commas and the result is stored in a list. We now have a list of items, where each number is still a string. The loop then for
converts each element of the string to numbers.
source to share
Regular expression and list:
Regular expression: there \d+
will be one or more repetitions ( +
) or previous RE
, so in this case a digit
( \d
). So, we can use this in your string, finding all matches for this with re.findall()
.
However, this will return list
ints
: 1
, 2
and 12
, but as a line, so we can use a list comprehension to convert them to type int
.
Your code might look something like this:
import re
s = "[1, 2, 12]\n"
l = [int(i) for i in re.findall("\d+", s)]
print(l)
This will give a list: [1, 2, 12]
source to share