validation - Flexible numeric string parsing in Python -
Is there a Python library which is supported by the built-in float () function to parse and validate more numerical strings than helps? For example, in addition to simple numbers (1234.56) and scientific notation (3.2 e 15), I want to be able to parse the formats:
- Number with commas: 2,147,483,647
- Large number: 5.5 billion
- excerpt: 1/4
I did some search and found nothing, though I would wonder if A library was not already present. If you want to change the "localized" numbers such as the American "2,147,483,647" form, from the module you < Code> atof () function. Example:
Import Locale locale.setlocale (locale.LC_NUMERIC, 'en_US') print locale.atof ('1,234,456.23') # print 1234456.23
For the variants in the form, Python now handles them directly (since version 2.6); They can also be made of string:
partially import xration x = fraction ('1/4') print float (x) # 0.25
< P> In this way, you can parse the number written in one of the first three ways, only with the help of the above two standard modules: Try: num = float (num_str) ) Exclude ValueError: Try: num = locale.atof (num_str) Exclude ValueError: Try: num = float (fractions (num_str)) Exclude ValueError: Increase exception (" # 'Num' has the numeric value of 'num_str' in the number # or '42 billion'.
Comments
Post a Comment