Reputation:
I made a script with BeautifulSoup4 that retrieves the price of a crypto-currency from coinmarketcap.
The text I get is in a string:
result = $3.75
how can I convert the result to float? I have to delete the $, how to do with a split?
result_without_dollar = result.split("$")
I tried but I only get back """.
I'd like to get
price = 3.75 , and price.type is float
Upvotes: 1
Views: 356
Reputation: 163287
You could also be a bit more specific about the value of result, and check the format of the string first, matching $
and capturing the numerical value in group 1.
\$(\d+(?:\.\d+)?)$
The pattern matches:
\$
Match $
(
Capture group 1
\d+
Match 1+ digits(?:\.\d+)?
Match an optional decimal part)
Close group 1$
End of stringIf the pattern matches, print group 1.
import re
result = "$3.75"
m = re.match(r"\$(\d+(?:\.\d+)?)$", result)
if m:
fl = float(m.group(1))
print(fl)
Output
3.75
Upvotes: 1
Reputation: 4975
I assumed that the string in question is 'result = $3.75'
, not clear from the question.
Find the position of the $
symbol and then slice the string.
s = 'result = $3.75'
price = float(s[s.find('$')+1:])
Output
3.75
Upvotes: 0
Reputation: 161
If you insist on using split()
you can do this like this:
result_without_dollar = float(result.split('$')[1])
Notice that split()
returns a list
.
However, you can achieve this more simply like this:
result_without_dollar = float(result[1:])
Upvotes: 2