How can I convert a string list to a list of ints?

时间:2017-08-05 11:03:54

标签: python python-2.7

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 the solution:

new_list = []
for char in line:
    try:
        new_list.append(int(char))
    except ValueError:
        pass

But this doesn't work in the case of numbers with more than one digit. Is there an inbuilt/better way to do this? Thanks

3 个答案:

答案 0 :(得分:2)

new_list = [int(num) for num in line.strip('[]\n').split(', ')]

A more readable solution will 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))

First line is stripped of the enclosing brackets and newline characters. Then the remaining string is split on commas and the result is saved in a list. Now we have a list of elements where each number is still a string. Then the for loop converts each of the string element into numbers.

答案 1 :(得分:0)

You can use regex:

import re
line = "[1, 2, 12]\n"
new_list = []
for char in re.findall("\d+", line):
    try:
        new_list.append(int(char))
    except ValueError:
        pass
print(new_list)

result: [1, 2, 12].

答案 2 :(得分:0)

Regex and list comprehension:

The regex: \d+ will one or more repetitions (+) or the previous RE so in this case a digit (\d). So, we can use this on your string by finding all matches for this with re.findall().

However, this will return a list of the ints: 1, 2 and 12 but as strings so we can use a list comprehension to convert these into the type int.

Your code could 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 the list: [1, 2, 12]