2

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'.

1
  • 8
    Does 'a_b_c'.rsplit('_', 1) work for you? Commented Oct 5, 2015 at 17:11

2 Answers 2

4

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')
Sign up to request clarification or add additional context in comments.

3 Comments

I'm going to downvote this, because it is a copy of a previous response.
@AlexReynolds well, this is a poor reason for the downvote. And this answer is not a copy of the comment.
@AlexReynolds: a comment is not a response, nor can I help that someone chose to use a comment. I did not base this answer on the comment. Moreover, my answer includes another alternative not mentioned in the comment. I would appreciate voting to happen on the helpfulness of an answer instead.
2
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 _.

3 Comments

Do note that this is overly complicated and and inefficient when you can just use standard methods like str.rsplit() and str.rpartition().
As a general approach, it is a more interesting and broadly applicable solution. +1
@AlexReynolds: The approach is better covered by the 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.