Use .rsplit()
or .rpartition()
instead:
s.rsplit(',', 1)
s.rpartition(',')
str.rsplit()
lets you specify how many times to split, while str.rpartition()
only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.
Demo:
>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')
Both methods start splitting from the right-hand-side of the string; by giving str.rsplit()
a maximum as the second argument, you get to split just the right-hand-most occurrences.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…