extracting numbers with decimal places from a string

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Jan 12 01:45:28 CET 2015


Thomas 'PointedEars' Lahn wrote:

> This is safer:
> 
> | >>> from re import split
> | >>> split(r'\s*,\s*', '1.23, 2.4, 3.123')
> | ['1.23', '2.4', '3.123']

Safer, slower, and unnecessary.

There is no need for the nuclear-powered bulldozer of regular expressions
just to crack this tiny peanut. We can split on commas, and then strip
whitespace:

py> values = "    1.234   ,    4.5678,   9.0123  ,4.321,0.9876  "
py> [s.strip() for s in values.split(',')]
['1.234', '4.5678', '9.0123', '4.321', '0.9876']


but in fact, we don't even need that, since float is perfectly happy to
accept strings with leading and trailing spaces:

py> float('            1.2345              ')
1.2345


-- 
Steven




More information about the Python-list mailing list