Andrew Tran
Andrew Tran

Reputation: 57

How to convert a string list to an int list?

I have this list

['456-789-154','741-562-785','457-154-129']

I want to convert it to int list like this:

[456,789,154,741,562,785,457,154,129]

Please help!!

I tried:

list = [item.replace("-",",") for item in list)
list = [item.replace("'","") for item in list)

But I don't know why the second line is not working.

Upvotes: 1

Views: 95

Answers (3)

Timur Shtatland
Timur Shtatland

Reputation: 12347

Use re.findall to return all stretches of digits, then flatten the list of lists and convert to int:

import re
strs = ['456-789-154','741-562-785','457-154-129']
nums = [int(num) for sublist in (re.findall(r'\d+', s) for s in strs) for num in sublist]
print(nums)
# [456, 789, 154, 741, 562, 785, 457, 154, 129]

Upvotes: 0

Stan11
Stan11

Reputation: 284

You can use the following approach

my_list = ['456-789-154','741-562-785','457-154-129']
new_list = []
sub_list = []
for item in my_list:
    sub_list = item.split("-")
    for item in sub_list:
        new_list.append(int(item))


print(new_list)

Output

[456, 789, 154, 741, 562, 785, 457, 154, 129]

Upvotes: 0

Aplet123
Aplet123

Reputation: 35512

Use a double list comprehension:

l = ['456-789-154','741-562-785','457-154-129']
num_list = [int(y) for x in l for y in x.split("-")]
print(num_list) # [456, 789, 154, 741, 562, 785, 457, 154, 129]

Upvotes: 4

Related Questions