Issue
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
Solution
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])
Answered By - mhhabib Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.