Reputation: 69
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
Reputation: 8752
Use int()
and a list comprehensions:
>>> i = ['1', '2', '3']
>>> [int(k) for k in i]
[1, 2, 3]
Upvotes: 10
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