0

I take the current exchange rate from the bank's website as a string and I want to convert this string into a number for further calculations and I want to do it as beautifully as possible.

How to convert the string 77,4651 $ to 77.4651 in float format without using func 'replace'?

kirastel
  • 17
  • 4

2 Answers2

1

Use float regular expression to make sure, that you get the float number

txt = "77.4651 $"
x = float(re.search("[-+]?[0-9]*(?:\.?[0-9]*)[1]", txt).string)

or less safe split by spaces

float("77.4651 $".split("\s+")[0])
Alex
  • 106
  • 8
1

Regex would be useful here to account for varying formats:

import re
float('.'.join(re.findall('[0-9]+', "77,4651 $")))
Bjarke Kingo
  • 368
  • 4
  • 10