Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python seperate numbers where no obvious seperation symbol is vissible

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading