How to turn all items in a string list into integers?

Asked

Viewed 947 times

-4

I have a list containing "n" elements like str. However, I need to make these elements come whole. How can I do this ?

For example, I have this list here:

trechos = conteudo[2:len(conteudo)]

Turns out I can’t just push it like this:

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

Because python is an error. How can I turn each value into an integer ? And then pass these integer values to a new list ?

  • Again the same question? You even took the trouble to read what you were told in the other question?

2 answers

1

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

0

Try this:

lista_inicial = ["12", "-4", "-232", "7", "1478"]

lista_final = [int(i) for i in lista_inicial]

print(lista_final)

Output:

[12, -4, -232, 7, 1478]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.