Split a string and get a single element in Python

avatar

Borislav Hadzhiev

Last updated: Jun 25, 2022

banner

Photo from Unsplash

Split a string and get a single element in Python #

To split a string and get a single element:

  1. Use the str.split() method to split the string into a list.
  2. Access the list element at the specific index.
  3. Assign the result to a variable.
main.py
my_str = 'one_two_three_four' first = my_str.split('_', 1)[0] print(first) # 👉️ one second = my_str.split('_')[1] print(second) # 👉️ two third = my_str.split('_')[2] print(third) # 👉️ three last = my_str.rsplit('_', 1)[-1] print(last) # 👉️ four

The first example uses the str.split() method to get the first element from the list.

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.

This is useful when you need to get the first element only.

main.py
my_str = 'one_two_three_four' # 👇️ ['one', 'two_three_four'] print(my_str.split('_', 1))

The second example uses the str.split() method without providing a value for the maxsplit argument and accesses the list item at index 1.

main.py
my_str = 'one_two_three_four' second = my_str.split('_')[1] print(second) # 👉️ two

Indexes in Python are zero-based, so the first item in a list has an index of 0, the second an index of 1, etc.

If you need to get the last element after splitting a string, use the str.rsplit() method instead.

main.py
my_str = 'one_two_three_four' last = my_str.rsplit('_', 1)[-1] print(last) # 👉️ four

The rsplit method is very similar to split, but it splits from the right.

Note that we also provided a value for the maxsplit argument to split the string from the right only once.

main.py
my_str = 'one_two_three_four' # 👇️ ['one_two_three', 'four'] print(my_str.rsplit('_', 1))

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

main.py
my_str = 'one_two_three_four' my_list = my_str.split('?') print(my_list) # 👉️ ['one_two_three_four']
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.