3

I have a string built from a few segments, which are not separated, but not overlap. This looks like that:

<python><regex><split>

I would like to split in into:

<python>, <regex>, <split>

I'm looking for the most efficient way to do that, and in the same time with as little code as possible. I could change '>' into '> ' etc., but I don't want to do any redundant operations. Is it possible to use regex to do that?

0

3 Answers 3

7

Try re.findall:

import re
your_string = '<python><regex><split>'
parts = re.findall(r'<.+?>', your_string)  
print parts # ['<python>', '<regex>', '<split>']
Sign up to request clarification or add additional context in comments.

1 Comment

This is the function I needed
2
>>> re.sub(r'<(.+?)>',r'<\1>,','<python><regex><split>')[:-1]
'<python>,<regex>,<split>'

Comments

1

If your input data is really that simple, you can just use the .replace() method that's built into strings.

>>> '<python><regex><split>'.replace('><', '>, <')
'<python>, <regex>, <split>'

If it's more complex, you should give a better example of input/expected output.

2 Comments

It's a bit redundant, because it requires to modify the string only to split it afterwards, I'd like to avoid such operation if possible.
Ah, I misunderstood your question. You want the result to be a list or similar which contains each of the elements you're looking for then ?

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.