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.
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)
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
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.
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)
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