Extract the price from a string yields ValueError: could not convert string to float: '.95.00'

Question:

I’m trying to extract a price value as float in python. The price comes as Rs.95.00

one = float(''.join(c for c in price_laughs if (c.isdigit() or c =='.')))
print(one)

I tried to extract the price using the following code, but since there’s a ‘.’ at the beginning, i’m unable to get the value as 95.00. How can i extract the price as a float value.

Asked By: Dilki Sasikala

||

Answers:

If price is always prefixed by Rs. then simply substring it and you are done:

price = 'Rs.95.00'
val = float(price[3:])
print(val)
Answered By: Marcin Orlowski

If the value is always going to contain Rs., one way is to split one time from left passing maxsplit=1 then to get the last value.

>>> v='Rs.95.00'
>>> float(v.split('.', 1)[-1])
95.0
Answered By: ThePyGuy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.