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:
['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']