0

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.

1
  • 1
    Is 1,211 supposed to be "1 point 211" or "1 thousand 211"? Commented Nov 26, 2016 at 9:56

3 Answers 3

4

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] 
Sign up to request clarification or add additional context in comments.

4 Comments

it is 1211 and not 1.211. What should I do in this case?
In this case, i.replace(',', '')
Nice solutions, but I don't understand why you need to form the list of floats and then list of int. Why don't you form a list of int directly?
@AhsanulHaque my initial approach was based on a confusion of OPs requirements. The float needs to be mapped first because int cannot transform a str in the form of a float.
2

Do it with a simple list comprehension.

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

Comments

1

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.