PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 10, 2022

[FIXED] How to convert percentage to decimal when it is in list

 August 10, 2022     decimal, list, percentage, python-3.x     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing