data_person
data_person

Reputation: 4470

list of string to int conversion

I want to convert a list of python elements from str to int.

My initial list looks like this:

l1 = ['723', '124', '1,211', '356']

The code I tried:

l1 =  list(map(int, l1))

Resulted in an error that tells me:

ValueError: invalid literal for int() with base 10: '1,211'

Alternatively, I tried maping with float:

l1 =  list(map(float, l1))

but, this also resulted in an error:

ValueError: could not convert string to float: '1,211'

I have tried both int and float in the code using map function. Can anyone correct me on where I'm going wrong.

Upvotes: 0

Views: 72

Answers (3)

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160367

Mapping either int or float to a value containing ',' will fail as converting strs to floats or ints has the requirement that they represent correctly formed numbers (Python doesn't allow ',' as separators for floats or for thousands, it conflicts with tuples)

If ',' is a thousands separator, use replace(',', '') (as @tobias_k noted) in the comprehension you supply to map and apply the int immediately:

r = list(map(int , (i.replace(',', '') for i in l1)))

to get a wanted result for r of:

[723, 124, 1211, 356]

Upvotes: 4

Taufiq Rahman
Taufiq Rahman

Reputation: 5704

This might help:

l1 = ['723', '124', '1,211', '356']
l1 = [int(i.replace(',','')) for i in l1]
for x in l1:
    print("{:,}".format(x))

Output:

723
124
1,211
356

Upvotes: 1

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

Do it with a simple list comprehension.

>>> l1 = ['723', '124', '1,211', '356']
>>> [int(i.replace(',','')) for i in l1]
[723, 124, 1211, 356]

Upvotes: 2

Related Questions