How to turn all items in a list of strings into integers?

-3

I have a list that contains "n" elements of type str . However, I need to get these elements to be integers. How can I do this?

For example, I have this list here:

trechos = conteudo[2:len(conteudo)]

It turns out that I can not just force it like this:

int(conteudo[2:len(conteudo)])

Because python gives error. How can I make each value integer? And then pass those integer values to a new list?

    
asked by anonymous 30.11.2017 / 21:01

1 answer

2
items = ['1', '2', '-10', 'A', '1234567890']

for item in items:
    print('{} type: {}'.format(item, type(item)))

int_items = [int(value) for value in items if value.lstrip('-').isdigit()]

for item in int_items:
    print('{} type: {}'.format(item, type(item)))

output:

1 type: <class 'str'>
2 type: <class 'str'>
-10 type: <class 'str'>
A type: <class 'str'>
1234567890 type: <class 'str'>

1 type: <class 'int'>
2 type: <class 'int'>
-10 type: <class 'int'>
1234567890 type: <class 'int'>

Running on IDEONE

    
30.11.2017 / 21:13