Split a string without removing the delimiter in Python

avatar

Borislav Hadzhiev

Last updated: Jun 24, 2022

banner

Check out my new book

Split a string without removing the delimiter in Python #

To split a string without removing the delimiter:

  1. Use the str.split() method to split the string into a list.
  2. Use a list comprehension to iterate over the list.
  3. On each iteration, add the delimiter to the item.
main.py
my_str = 'one_two_three_four' delimiter = '_' my_list = [x+delimiter for x in my_str.split(delimiter) if x] # 👇️ ['one_', 'two_', 'three_', 'four_'] print(my_list)

The first step is to use the str.split() method to split the string into a list.

main.py
my_str = 'one_two_three_four' delimiter = '_' # 👇️ ['one', 'two', 'three', 'four'] print(my_str.split(delimiter))

Once we have a list of strings, we can use a list comprehension to iterate over it adding the delimiter to each list item.

main.py
my_str = 'one_two_three_four' delimiter = '_' my_list = [x+delimiter for x in my_str.split(delimiter) if x] # 👇️ ['one_', 'two_', 'three_', 'four_'] print(my_list)

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

The str.split() method splits the original string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)

If you need to split the delimiters as separate items in the list, use the re.split() method.

main.py
import re my_str = 'one_two_three_four' my_list = re.split(r'(_)', my_str) # 👇️ ['one', '_', 'two', '_', 'three', '_', 'four'] print(my_list)

The re.split method takes a pattern and a string and splits the string on each occurrence of the pattern.

The parenthesis in the regular expression match whatever is inside and indicate the start and end of a group.

The group's contents can still be retrieved after the match.

Even though, we split the string on the underscore, we still include the underscores in the result.

Use the search field on my Home Page to filter through my more than 3,000 articles.