To split a string and keep the splitting pattern, we can use regex in combination with the re module in Python.
For example, let's say we have the following string:
main.py60 chars2 lines
We want to split the string where there is a comma , and keep the comma in the resulting list. We can achieve this as follows:
main.py269 chars10 lines
In the code above, we first import the re module, then define the splitting pattern using regex. The r in front of the pattern indicates a raw string which is used to avoid escaping special characters like the backslash \.
We then use the re.split() method, passing in the splitting pattern and the string to split as arguments. The resulting list retains the split pattern, in this example, the comma ,.
gistlibby LogSnag