2

hi I'm trying to convert this list of strings: lists=['111,222','121,121'] into a list of integers but keep running into errors, any advice would be helpful. I've tried:

results=[int(i) for i in lists]
print(results)

but keep getting "invalid literal for int() with base 10: '111,222'"

4
  • 9
    Please add expected, output and what have you tried... Also this is a pretty common question, are you sure there isn't some other post that answers it? Commented Dec 7, 2019 at 0:18
  • What integer do you expect the string "111,222" to be converted into? Commented Dec 7, 2019 at 0:22
  • 111222, but I want it as an int() instead of a str() Commented Dec 7, 2019 at 0:23
  • Well, Python doesn't support a thousands separator when converting strings to integers. Commented Dec 7, 2019 at 0:32

2 Answers 2

4

You need to remove the commas, for example:

lists=['111,222','121,121']
result = [int(s.replace(',', '')) for s in lists]
print(result)

Output

[111222, 121121]
Sign up to request clarification or add additional context in comments.

Comments

3

This should work

import re

lists=['111,222','121,121']
results = [ int("".join(re.findall('[0-9]+', element))) for element in lists ] 

# results = [111222, 121121]

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.