extracting numbers with decimal places from a string

Thomas 'PointedEars' Lahn PointedEars at web.de
Sun Jan 11 17:20:49 EST 2015


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']

-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.



More information about the Python-list mailing list