Reputation:
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:
print(string.split(' ')[-2:])
Output:
['356.0648792', '-80.1770250']
Upvotes: 0
Views: 181
Reputation: 3
Im new in python, i love @Abdul Niyas P M
@Selcuk
answers.
string = 'ESO 12-4 356.0648792 -80.1770250'
l = len(string.split())
print(string.rsplit(maxsplit=l-2))
#['ESO 12-4', '356.0648792', '-80.1770250']
Upvotes: 0
Reputation: 24582
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']
Upvotes: 3
Reputation: 1
You can use regexp to extract the "12-4" and use it to split the string
>>>import re
>>>string = 'ESO 12-4 356.0648792 -80.1770250'
>>>matched_string = re.findall(r'[0-9]+-[0-9]+', string)[0]
>>>[string.split(matched_string)[0] + ' ' + matched_string, string.split(' ')[-2] , string.split(' ')[-1]])
['ESO 12-4', '356.0648792', '-80.1770250']
Upvotes: -1
Reputation: 59184
You can reverse the string and use the maxsplit
argument of the .split()
method. Obviously you should also reverse the result in the end. Try this:
>>> [s[::-1] for s in string[::-1].split(" ", 2)[::-1]]
['ESO 12-4', '356.0648792', '-80.1770250']
Edit: You should probably use the .rsplit()
method as @AbdulNiyasPM posted instead of using this convoluted method.
Upvotes: 0