Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Splitting a string and retaining the separator (without RegEx)

I have the following string foo:

foo = 'F9B2Z1F8B30Z4'

Without using re, I’d like to split on ‘F’ and then add ‘F’ back to the resulting list.

My attempt is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['F'+elem for elem in foo.split('F')]

This gives us:

['F', 'F9B2Z1', 'F8B30Z4']

But, I was expecting:

['F9B2Z1', 'F8B30Z4']

Is it possible to modify the list comprehension to catch this case? If not, is there another approach that I can use?

Thanks!

>Solution :

Actually your problem might be more amenable to use re.findall:

foo = 'F9B2Z1F8B30Z4'
parts = re.findall(r'F[^\WF]*', foo)
print(parts)  # ['F9B2Z1', 'F8B30Z4']

The regex pattern matches a leading F followed by zero or more word characters, which are not F.

To do this using non regex split, we can slightly modify your list comprehension to only retain non empty string elements from the split:

parts = ['F' + elem for elem in foo.split('F') if elem != '']
print(parts)  # ['F9B2Z1', 'F8B30Z4']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading