Split a string and get the first element in Python

avatar

Borislav Hadzhiev

Last updated: Jun 25, 2022

banner

Photo from Unsplash

Split a string and get the first element in Python #

Use the str.split() method with maxsplit set to 1 to split a string and get the first element, e.g. my_str.split('_', 1)[0]. The split() method will only perform a single split when maxsplit is set to 1.

main.py
my_str = 'a_b_c_d' last = my_str.split('_', 1)[0] print(last) # 👉️ 'a'

The example shows how to split the string and get the first element.

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.

main.py
my_str = 'a_b_c_d' # 👇️ ['a', 'b_c_d'] print(my_str.split('_', 1))

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

main.py
my_str = 'abcd' last = my_str.split('_', 1)[0] print(last) # 👉️ 'abcd'

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

main.py
my_str = '_a_b_c_d_' # 👇️ ['', 'a_b_c_d_'] print(my_str.split('_', 1)) last = my_str.split('_', 1)[0] print(last) # 👉️ ""

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

main.py
my_str = '_a_b_c_d_' # 👇️ ['a', 'b_c_d'] print(my_str.strip('_').split('_', 1)) last = my_str.strip('_').split('_', 1)[0] print(last) # 👉️ "a"

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

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.