Split a string on the first occurrence in Python

avatar

Borislav Hadzhiev

Last updated: Jun 24, 2022

banner

Photo from Unsplash

Split a string on the first occurrence in Python #

Use the str.split() method with maxsplit set to 1 to split a string on the first occurrence, e.g. my_str.split('-', 1). The split() method only performs a single split when the maxsplit argument is set to 1.

main.py
my_str = 'one-two-one-three' my_list = my_str.split('-', 1) print(my_list) # 👉️ ['one', 'two-one-three'] print(my_list[0]) # 👉️ one print(my_list[1]) # 👉️ two-one-three # 👇️ if you need to unpack values into variables first, second = my_list print(first) # 👉️ one print(second) # 👉️ two-one-three

The example splits the string on the first occurrence of a hyphen, but you could use any other separator.

The str.split() method splits the 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)

When the maxsplit argument is set to 1, at most 1 split is done.

If the separator is not found in the string, a list containing only 1 element is returned.

main.py
my_str = 'one' my_list = my_str.split('-', 1) print(my_list) # 👉️ ['one']

If your string starts with the specific separator, you might get a confusing result.

main.py
my_str = '-one-two-one-three-' my_list = my_str.split('-', 1) print(my_list) # 👉️ ['', 'one-two-one-three-']

You can use the str.strip() method to remove the leading or trailing separator.

main.py
my_str = '-one-two-one-three-' my_list = my_str.strip('-').split('-', 1) print(my_list) # 👉️ ['one', 'two-one-three']

We used the str.strip() method to remove any leading or trailing hyphens from the string before calling the split() method.

If you need to assign the results from the list to variables, unpack the values from the list.

main.py
my_str = 'one-two-one-three' my_list = my_str.split('-', 1) print(my_list) # 👉️ ['one', 'two-one-three'] # 👇️ if you need to unpack values into variables first, second = my_list print(first) # 👉️ one print(second) # 👉️ two-one-three

The first and second variables store the first and second items from the list.

When using this approach, we have to be sure to declare exactly as many variables as there are items in the iterable.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.