Borislav Hadzhiev
Last updated: Jun 24, 2022
Check out my new book
To split a string without removing the delimiter:
str.split()
method to split the string into a list.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.
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.
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:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At most maxsplit splits are done (optional) |
If you need to split the delimiters as separate items in the list, use the
re.split()
method.
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 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.