Home > Back-end >  Python seperate numbers where no obvious seperation symbol is vissible
Python seperate numbers where no obvious seperation symbol is vissible

Time:08-18

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.

CodePudding user response:

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