BForce01
BForce01

Reputation: 69

How can I convert a list of strings into numeric values?

How can I convert a list of strings (each of which represents a number, i.e. [‘1’, ‘2’, ‘3’]) into numeric values.

Upvotes: 0

Views: 614

Answers (6)

Lennart Regebro
Lennart Regebro

Reputation: 172209

Try this method:

>>> int('5')
5

Upvotes: 2

Tadeusz A. Kadłubowski
Tadeusz A. Kadłubowski

Reputation: 8335

map(int, ["1", "2", "3"])

gives

[1, 2, 3]

Upvotes: 16

alanlcode
alanlcode

Reputation: 4238

Like this:

map(int, ['1', '2', '3'])

Upvotes: 2

Anoop
Anoop

Reputation: 1435

a=['1','2','3']
map(lambda x: int(x),a)

> [1, 2, 3]

Upvotes: 0

Derek Swingley
Derek Swingley

Reputation: 8752

Use int() and a list comprehensions:

>>> i = ['1', '2', '3']
>>> [int(k) for k in i]
[1, 2, 3]

Upvotes: 10

Dan Goldsmith
Dan Goldsmith

Reputation: 424

As Long as the strings are of the form '1' rather than 'one' then you can use the int() function.

Some sample code would be

strList = ['1','2','3']
numList = [int(x) for x in strList]

Or without the list comprehension

strList = ['1','2','3']
numList = []
for x in strList:
    numList.append(int(x))

Both examples iterate through the list on strings and apply the int() function to the value.

Upvotes: 5

Related Questions