Splitting a string and retaining the separator (without RegEx) [duplicate]

73
April 10, 2022, at 9:20 PM
This question already has answers here:
Python split() without removing the delimiter [duplicate] (4 answers)
Closed 2 months ago.

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!

Answer 1

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']
Answer 2

Without regex we can do it by replacing the F with some other delimiter before it then spiting it at the replaced delimiter and filtering empty strings

[elem for elem in foo.replace("F","-F").split("-") if elem]

Rent Charter Buses Company
READ ALSO
How to groupby a column and count the number of unique values in another column

How to groupby a column and count the number of unique values in another column

I have the following dataframeI need to groupby the ngram, and for each group, count how many unique documents are present in the DocID column

111
How to replace pixel data in same DICOM file using pyDicom to read it again with any DICOM viewer?

How to replace pixel data in same DICOM file using pyDicom to read it again with any DICOM viewer?

I want to read some DICOM files, so I'm testing pydicom for my work, which I think is considerably useful

124
Selecting dropdown values using Excel(OpenPyXl) - Selenium-Python

Selecting dropdown values using Excel(OpenPyXl) - Selenium-Python

I am having a web application which is having multiple dropdownsFor inputting the values for the other text fields, I am reading the data from excel to comply with data driven testing

113