Pierre Barbier de Reuille schrieb:
Mmmhhh ... not strictly one line but ...

import re

float_str = re.compile(r"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$")

val = [ ( (float_str.match(s) and [float(s)]) or [s])[0] for s in l2 ]

It's not really "readable" but well ... it works ^_^

Pierre


This can be done in strictly 1 line (having already imported re):

>>> l = ['1','2','3','abc','0', '','4']
>>> [(re.match(r"^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$",s) and [float(s)] or [s])[0] for s in l]
[1.0, 2.0, 3.0, 'abc', 0.0, '', 4.0]


or, if one doesn't have to take into account exponential format:

>>> [(x and not[y for y in x if y not in "0123456789."] and x.count(".")<2 and [float(x)] or [x])[0] for x in l]
[1.0, 2.0, 3.0, 'abc', 0.0, '', 4.0]
>>>


hmmm, unfortunately "Useless Python" isn't maintained anymore...

(^o^)

Gregor
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to