简体   繁体   中英

Python: extract number from String

I'm new to Python and I was trying to get a "price tag String" to get converted into a float, so I can easily compare the result with other prices. I searched for 2 hours for a answer for this "simple problem", but none of them fitted my needs.

So basically, I have a price like this:

1.222.333,44 EUR

(comma and period swapped because I live in Germany, which is also pretty annoying)

And I want to get this for easy comparing:

1222333.44

The main idea is to compare prices, which is my school project.
I used to do everything with php, which worked, but was way too slow.

If you have a more elegant or simple way, please let me know.

This work for the specific case you provided:

float(s.replace('.', '').replace(',', '.').split(' ')[0])

It requires:

  1. Periods in price are only separators;
  2. Only one comma in price and is just a decimal mark;
  3. The price comes first and is separated from other strings by a whitespace.

Just to mention in case people need more generalized solution, hiro protagonist's answer using locale is very helpful when you need a simple way to switch between numeral systems during coding or when maintaining your codes.

you can use your (or any) locale to convert a string to a 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 may not even have to specify the locale.

in your case you may need to split the currency (EUR) part away:

price = '1.222.333,44 EUR'
price_float = locale.atof(price.split()[0])
print(price_float) # -> 1222333.44

note: it may be enough not to set LC_ALL but just LC_NUMERIC to what you need.

If your string is "1.222.333,44 EUR"

prince = "1.222.333,44 EUR"
price = price[:-4]
price = price.replace(".","").replace(",",".")
floatprice = float(price)

If it is just like this "1.222.333,44"

floatprice = float("1.222.333,44".replace(".","").replace(",","."))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM