extracting numbers with decimal places from a string

Grant Edwards invalid at invalid.invalid
Mon Jan 12 00:06:49 CET 2015


On 2015-01-11, Joel Goldstick <joel.goldstick at gmail.com> wrote:

> That's fine, but its different than your original question.  In your
> original question you had a string of floats separated by commas.  To
> solve that problem you need to first split the string on the commas:
>
> my_list = "1.23, 2.4, 3.123".split(",")
>
> that will give you ['1.23', '2.4', '3.123']

Well, almost:

$ python
Python 2.7.9 (default, Jan 11 2015, 15:39:24) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> "1.23, 2.4, 3.123".split(",")
['1.23', ' 2.4', ' 3.123']

Note the leating whitespace in two of the elements. In this case, the
leading whitespace is ignored if you pass the values to float():

>>>map(float,"1.23, 2.4, 3.123".split(","))
[1.23, 2.4, 3.123]

Or for you young folks who prefer the more long-winded version:

>>> [float(s) for s in "1.23, 2.4, 3.123".split(",")]
[1.23, 2.4, 3.123]

In other situations, the leading whitespace might matter.

-- 
Grant






More information about the Python-list mailing list