0

I have a list with about a hundred items. Some of them contain commas separating the thousand place. Example:

list = ['10', '1,000', '51,000', '500', '63,000']

I'm trying to convert the list into an int but am finding it difficult with these commas. Is there away to use .replace on the list or something. Thanks for the tips in advance.

  • 3
    `[int(x.replace(',', '')) for x in list]` ? And please don't use `builtin` names as user variables – han solo Mar 11 '19 at 14:15
  • See [How to convert a string to a number if it has commas in it as thousands separators?](https://stackoverflow.com/q/1779288/10077). – Fred Larson Mar 11 '19 at 14:19

4 Answers4

2

You could use a list comprehension, and extract integers from the strings using string.replace to remove all the ',':

l = ['10', '1,000', '51,000', '500', '63,000']
[int(s.replace(',','')) for s in l]
# [10, 1000, 51000, 500, 63000]
yatu
  • 86,083
  • 12
  • 84
  • 139
0

Because your elements in list are string, you can use string.replace().

mylist = ['10', '1,000', '51,000', '500', '63,000']

newlist = []
for n in mylist:
    newlist.append(n.replace(",",''))

The output type is also string:

newlist = ['10', '1000', '51000', '500', '63000']
YusufUMS
  • 1,506
  • 1
  • 12
  • 24
0
import re
list = ['10', '1,000', '51,000', '500', '63,000']

a = []
for p in list:
    x = re.compile(',')
    y = re.sub(x, '', p)
    print(y)
    a.append(int(y))

but Don't use a reserved word as a variable use any other variable instead of list

0
list1 = ['10', '1,000', '51,000', '500', '63,000']
list1 =[int(''.join(i.split(','))) for i in list1 ]
print(list1)
# output [10, 1000, 51000, 500, 63000]
sahasrara62
  • 10,069
  • 3
  • 29
  • 44