What's the recommended Python idiom for splitting a string on the last occurrence of the delimiter in the string? example:
# instead of regular split
>> s = "a,b,c,d"
>> s.split(",")
>> ['a', 'b', 'c', 'd']
# ..split only on last occurrence of ',' in string:
>>> s.mysplit(s, -1)
>>> ['a,b,c', 'd']
mysplit
takes a second argument that is the occurrence of the delimiter to be split. Like in regular list indexing, -1
means the last from the end. How can this be done?
I just did this for fun
>>> s = 'a,b,c,d'
>>> [item[::-1] for item in s[::-1].split(',', 1)][::-1]
['a,b,c', 'd']
Caution: Refer to the first comment in below where this answer can go wrong.
You can use rsplit
string.rsplit('delimeter',1)[1]
To get the string from reverse.
Source: Stackoverflow.com