error when conver string to float in python

Asked

Viewed 7,350 times

1

Hello I’m having a problem I’m not getting Contact string to float

the program takes the price of a dps game converts to string and position through the character and I am unable to convert


price =game.find(attrs="col search_price discounted responsive_secondr
price = str(price)
if not price[110] =="<":
    print("Sem Deconto:", price[101:109])
    print("Com Desconto:",float(price[104:109]))
else:
    print("Sem Deconto:", price[101:110])
    print("Com Desconto:",price[104:110])

Upshot

File "/home/Alison/Documents/program/Steam/search_steam.py", line 57, in price
print("Discounted:"float(price[104:109]))
Valueerror: could not Convert string to float: '36,99'

  • I don’t know python, but I’ll give my guess: Try to convert 36.90 instead of 36,99.

  • the worst that the program value returns values with 2 commas and even though 36.90 is also error

  • Yeah, you have to turn that comma into a point, I’ll create an answer for you to see how it would look.

2 answers

5


As I told you in the comment, the problem is that Python does not recognize the comma (,) as a representation of decimals, only the point (.), you can reverse this by using the replace, as Fabius answered. Would look this way:

print("Com Desconto:",float(price.replace(",",".")))

See working on Ideone.

  • You have the ability to use locale, there Python recognizes the comma: https://stackoverflow.com/a/13362256; as stated in the other answers and comments of this question in the international OS, this will change the settings of the locale current, and perhaps this can generate inconsistencies here and there

1

The String you are reading has the form '36.99' (DD,DD), this cannot be converted to float by this python function. You need to transform your string to the form 'DD.DD' (36.99) before making the conversion.

You could do this with python character replacement functions (such as replace).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.