Python: extract number from String
I am new to Python and I was trying to get the "String price tag" to convert it to float so I can easily compare the result with other prices. I searched for 2 hours for an answer to this "simple problem" but none of them fit my needs.
Basically, I have a price like this:
1.222.333,44 EUR
(comma and period are reversed because I live in Germany, which is also very annoying)
And I want to get this for easy comparison:
1222333.44
The main idea is to compare prices, which are my school project.
I did everything with php that worked but was too slow.
If you have a more elegant or simpler way, please let me know.
source to share
This work for the specific case you provided:
float(s.replace('.', '').replace(',', '.').split(' ')[0])
This requires:
- The periods in the price are just separators;
- There is only one comma in the price and is only a decimal point;
- The price comes first and is separated from other lines by a space.
Just to mention if people are in need of a more general solution, hiro protagonist's answer , using locale
, is very helpful when you need an easy way to switch between digital systems while coding, or while saving your codes.
source to share
you can use your (or any) locale to convert to float :
import locale
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
print(locale.atof('1.222.333,44')) # -> 1222333.44
depending on your default locale, you don't even need to specify the locale.
in your case, you may need a split
part of the currency (EUR):
price = '1.222.333,44 EUR'
price_float = locale.atof(price.split()[0])
print(price_float) # -> 1222333.44
note: it's enough to install LC_ALL
, but just LC_NUMERIC
what you need.
source to share