extracting numbers with decimal places from a string

Joel Goldstick joel.goldstick at gmail.com
Sun Jan 11 23:54:52 CET 2015


On Sun, Jan 11, 2015 at 5:20 PM, Thomas 'PointedEars' Lahn
<PointedEars at web.de> wrote:
> Joel Goldstick wrote:
>
>> my_list = "1.23, 2.4, 3.123".split(",")
>>
>> that will give you ['1.23', '2.4', '3.123']
>
> No, it gives
>
> | $ python
> | Python 2.7.9 (default, Dec 11 2014, 08:58:12)
> | [GCC 4.9.2] on linux2
> | Type "help", "copyright", "credits" or "license" for more information.
> | >>> my_list = "1.23, 2.4, 3.123".split(",")
> | >>> my_list
> | ['1.23', ' 2.4', ' 3.123']
> | >>>
>
> | $ python3
> | Python 3.4.2 (default, Dec 27 2014, 13:16:08)
> | [GCC 4.9.2] on linux
> | Type "help", "copyright", "credits" or "license" for more information.
> | >>> my_list = "1.23, 2.4, 3.123".split(",")
> | >>> my_list
> | ['1.23', ' 2.4', ' 3.123']
> | >>>
>
> In order to get the result you described, one needs at least
>
> | >>> '1.23, 2.4, 3.123'.split(', ')
> | ['1.23', '2.4', '3.123']
>
> This is safer:
>
> | >>> from re import split
> | >>> split(r'\s*,\s*', '1.23, 2.4, 3.123')
> | ['1.23', '2.4', '3.123']
>

I'm not sure what you are trying to point out as your examples confirm
my code.  Am I missing something.

As for feeding a beginner regex solutions, I'm on the side that this
is a terrible idea.  Regex is not something a beginner should worry
about!
> --
> PointedEars
>
> Twitter: @PointedEars2
> Please do not cc me. / Bitte keine Kopien per E-Mail.
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com



More information about the Python-list mailing list