Regex for parsing list of floating numbers in python
What's the best why to parse lists of floating numbers separated by space in python?
I have rows of this kind that will come out from a source:
string = " 4 1.6 8.29 0 0 3.55e-15 -1.28e-13 "
with an unknown number of whitespaces separating the numbers and on the beggining or end of the string.
I usually just used numbers = map(fl开发者_JS百科oat, string.split(" "))
when I could guarantee that there would be only one space between the numbers, and that there would not be spaces in the beginning or end of the string. I'm not skilled in regexps, but someone suggested me to use re.split("\s+", string)
but that doesn't work because sometimes I got empty strings in the beggining of the resulting list.
I'm using now: re.split("\s+")
but that doesn't work because sometimes I got empty strings in the beggining of the resulting list.
I'm using now:
res = map(float, re.findall("\d+\S*\d*", string)
which is working somehow, but looks fragile and ugly to me. It can match many strings that will fail to produce numbers.
What's the best regexp pattern that will always match integers and floating point numbers with or without exponential notation so that I could use re.findall(patt, string)
and safely recover a list of numbers?
No regex is needed. Simply use string.split()
without any arguments; it will split on any amount of whitespace.
An example of using the str.split()
method with a list comprehension -- mildly more Pythonic, and IMHO clearer, than map
:
>>> string = " 4 1.6 8.29 0 0 3.55e-15 -1.28e-13 "
>>> floats = [float(x) for x in string.split()]
>>> floats
[4.0, 1.6000000000000001, 8.2899999999999991, 0.0, 0.0, 3.5500000000000001e-15,
-1.2800000000000001e-13]
精彩评论