I have the following string in python:
foo = 'a_b_c'
How do I split the string into 2 parts: 'a_b' and 'c'? I.e, I want to split at the second '_'
str.split('_') splits into 3 parts: 'a', 'b' and 'c'.
Use the str.rsplit() method with a limit:
part1, part2 = foo.rsplit('_', 1)
str.rsplit() splits from the right-hand-side, and the limit (second argument) tells it to only split once.
Alternatively, use str.rpartition():
part1, delimiter, part2 = foo.rpartition('_')
This includes the delimiter as a return value.
Demo:
>>> foo = 'a_b_c'
>>> foo.rsplit('_', 1)
['a_b', 'c']
>>> foo.rpartition('_')
('a_b', '_', 'c')
import re
x = "a_b_c"
print re.split(r"_(?!.*_)",x)
You can do it through re.Here in re with the use of lookahead we state that split by _ after which there should not be _.
str.rsplit() and str.rpartition().str.rsplit() and str.rpartition() methods. str.rsplit() lets you split more than once, which is harder to do with a regex. The regex is harder to comprehend, so maintenance of the codebase is now more complicated.
'a_b_c'.rsplit('_', 1)work for you?