Python seperate numbers where no obvious seperation symbol is vissible

Question:

I have a text file that I am trying to turn into something I can do math operations with.

The issue with the file is that some numbers are not seperated correctly like the following:

mylist = ['21', '0', '0-2.0000000000000E-001-6.0000000000000E+001']

Right now I have everything as a string and want to convert it to a float but before doing so I need seperate the last three numbers to get the following output:

mylist = ['21', '0', '0' , '-2.0000000000000E-001' , '-6.0000000000000E+001']

I need something that seperates the item in the list when a minus sign is present, except when the minus sign is preceded by E.

Asked By: livelysteak

||

Answers:

It should be checked against a few more examples, but a regular expression can do the trick:

>>> from re import findall
>>> findall(r'[+-]?d+(?:.d+)?(?:E[+-]d+)?', ' '.join(mylist))
['21', '0', '0', '-2.0000000000000E-001', '-6.0000000000000E+001']
Answered By: gimix
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.