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 – Split String correctly

string = 'ESO 12-4 356.0648792 -80.1770250'

I want it to be broken down into a list like this:

list = ['ESO 12-4', '356.0648792', '-80.1770250']

However, the first part ('ESO 12-4') can have multiple strings, so I thought to cut it off from the end.

My Code:

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

print(string.split(' ')[-2:])

Output:

['356.0648792', '-80.1770250']

>Solution :

I am assuming that you always have the string with the following format.

your_string = '<FIRST_PART(CAN CONTAIN SPACES)> <SECOND_PART(WITHOUT SPACES)> <THIRD_PART(WITHOUT SPACES)>'

If yes you could use rsplit(maxsplit=2) to get the desired output.

>>> string = 'ESO 12-4 356.0648792 -80.1770250'
>>> string.rsplit(maxsplit=2)
['ESO 12-4', '356.0648792', '-80.1770250']
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