Home > other >  How can I separate the first word of a string?
How can I separate the first word of a string?

Time:10-06

I made a script with beautiful soup4 that retrieves the price of a crypto-currency from coinmarketcap.

The text I get is in string:

result = $3.75

how can i convert result to float ? i have to delete the $ , how to do with 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

CodePudding user response:

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:])

CodePudding user response:

Try with

result_without_dollar=result.replace('$','')

CodePudding user response:

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

CodePudding user response:

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 string

If 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
  • Related