How to convert percentage to decimal when it is in list

Viewed 251
rstocks = ['5.57%','3.95%','5.26%','5.49%','-1,80%']

stocks =[]
for i in rstocks:
     stock = rstocks[i]//100
     stocks.append(stock)

It keeps showing

TypeError: list indices must be integers or slices, not str
2 Answers

There have two several errors in your code.

  • You may be mistakenly put the value -1,80% instead of -1.80%.
  • All the elements of your list are strings and strings have no integer division

To get integer division of your element of the list, first, you need to convert the element into integer then use operator. Look at my code below. I convert all the elements into float then multiplied it to 100.

rstocks = ['5.57%', '3.95%', '5.26%', '5.49%', '-1.80%']

stocks = []
for x in rstocks:
    stocks.append(float(x.strip('%'))*100)
print(stocks)

Output
[557.0, 395.0, 526.0, 549.0, -180.0]

Further you need to get integer value then you can typecast float to int.

int(float(x.strip('%'))*100)

Or typecast later all the elements of stocks.

print([int(s) for s in stocks])

I'm assuming that the value at last index on 'rstocks' is '-1.80%' instead of '-1,80%'. You can get a substring of the values in the loop and change the data type to float.

rstocks = ['5.57%','3.95%','5.26%','5.49%','-1.80%']
stocks =[]
for i in rstocks:
   stock = float(i[:-1])
   stocks.append(stock)
Related