How to Split Strings in Python Without Removing the Delimiter?

Estimated read time 2 min read

In Python, you can split strings without removing the delimiter character using the split() method of strings with a slight modification. The split() method by default removes the delimiter character from the resulting list of substrings. However, you can use a technique called “capturing groups” to include the delimiter character in the resulting list of substrings.

Here’s an example:

import re

my_string = "Hello,world;how are you today?"

delimiter_pattern = r"([,;])"

split_strings = re.split(delimiter_pattern, my_string)

result = [s for s in split_strings if s]


In this example, we first import the re module, which provides regular expression functionality in Python.

We then define the string we want to split, my_string, and the delimiter pattern we want to use to split the string. In this case, we use the regular expression pattern ([,;]), which matches either a comma or a semicolon, and captures the delimiter character in a group.

We then use the re.split() method to split the string using the delimiter pattern, and assign the result to split_strings.

To include the delimiter character in the resulting list of substrings, we use a list comprehension to filter out empty strings and keep only non-empty strings in the split_strings list.

The output of this example code would be:

['Hello', ',', 'world', ';', 'how are you today?']

Note that the delimiter characters are included in the resulting list of substrings. If you want to remove the empty strings from the resulting list of substrings, you can use a list comprehension with a condition to filter them out, as shown in the example above.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply