Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert string to number without 'replace' Python

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’?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading