Reputation: 22031
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'
.
Upvotes: 2
Views: 209
Reputation: 1124808
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')
Upvotes: 4
Reputation: 67988
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 _
.
Upvotes: 2