Split a String and get First or Last element in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
4 min

banner

# Table of Contents

  1. Split a String and get the First element in Python
  2. Split a string and get the Last element in Python
  3. Split a string and get the First element using partition()
  4. Split a string and get the Last element using rpartition()

# Split a string and get the First element in Python

To split a string and get the first element:

  1. Use the str.split() method, setting maxsplit to 1.
  2. Access the list element at index 0.
main.py
my_str = 'bobby_hadz_com' first = my_str.split('_', 1)[0] print(first) # ๐Ÿ‘‰๏ธ 'bobby'

split string and get first element

The code for this article is available on GitHub

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))

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(a_string) - 1.

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

main.py
my_str = 'abcd' first = my_str.split('_', 1)[0] print(first) # ๐Ÿ‘‰๏ธ 'abcd'

# Removing the leading and trailing separator before splitting

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)) first = my_str.split('_', 1)[0] print(repr(first)) # ๐Ÿ‘‰๏ธ ""

remove leading and trailing separator before splitting

The code for this article is available on GitHub

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)) first = my_str.strip('_').split('_', 1)[0] print(first) # ๐Ÿ‘‰๏ธ "a"

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

# Split a string and get the Last element in Python

To split a string and get the last element:

  1. Use the str.rsplit() method to split the string from the right.
  2. Set the maxsplit argument to 1.
  3. Access the list element at index -1.
main.py
my_str = 'bobby,hadz,com' last = my_str.rsplit(',', 1)[-1] print(last) # ๐Ÿ‘‰๏ธ 'com'

split string and get last element

The code for this article is available on GitHub

We used the rsplit() method to split the string from the right.

The str.rsplit() method returns a list of the words in the string using the provided separator as the delimiter string.

main.py
my_str = 'bobby hadz com' print(my_str.rsplit(' ')) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz', 'com'] print(my_str.rsplit(' ', 1)) # ๐Ÿ‘‰๏ธ ['bobby hadz', 'com']

The method takes the following 2 arguments:

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

Except for splitting from the right, rsplit() behaves like split().

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

The last step is to access the last element in the list by accessing the list item at index -1.

main.py
my_str = 'bobby,hadz,com,abc' last = my_str.rsplit(',', 1)[-1] print(last) # ๐Ÿ‘‰๏ธ 'abc'

Python indexes are zero-based, so the first character in a string has an index of 0, and the last character has an index of -1 or len(a_string) - 1.

# Split a string and get the Last element using split()

You can also use the str.split() method in a similar way.

main.py
my_str = 'bobby-hadz-com' last = my_str.split('-')[-1] print(last) # ๐Ÿ‘‰๏ธ 'com'

split string and get last element using split

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

main.py
my_str = 'bobby-hadz-com-' last = my_str.rsplit('-', 1)[-1] # ๐Ÿ‘‡๏ธ ['bobby-hadz-com', ''] print(my_str.rsplit('-', 1)) print(last) # ๐Ÿ‘‰๏ธ ""
The code for this article is available on GitHub

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

main.py
my_str = 'bobby-hadz-com-' last = my_str.strip('-').rsplit('-', 1)[-1] print(last) # ๐Ÿ‘‰๏ธ "com"

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

# Split a string and get the First element using partition()

You can also use the str.partition() method to split a string and get the first element.

main.py
my_str = 'bobby-hadz-com' result = my_str.partition('-')[0] print(result) # ๐Ÿ‘‰๏ธ bobby

The str.partition() method splits the string at the first occurrence of the provided separator.

main.py
my_str = 'bobby!hadz!com' separator = '!' # ๐Ÿ‘‡๏ธ ('bobby', '!', 'hadz!com') print(my_str.partition(separator))

The method returns a tuple containing 3 elements - the part before the separator, the separator, and the part after the separator.

If the separator is not found in the string, the method returns a tuple containing the string, followed by 2 empty strings.
main.py
my_str = 'bobby-hadz-com' # ๐Ÿ‘‡๏ธ ('bobby-hadz-com', '', '') print(my_str.partition('!'))

In our case, the expression would return the entire string if the separator is not contained in the string.

main.py
my_str = 'bobby-hadz-com' result = my_str.partition('!')[0] print(result) # ๐Ÿ‘‰๏ธ bobby-hadz-com

# Split a string and get the Last element using rpartition()

You can also use the str.rpartition method to split a string and get the last element.

main.py
my_str = 'bobby-hadz-com' result = my_str.rpartition('-')[-1] print(result) # ๐Ÿ‘‰๏ธ com
The code for this article is available on GitHub

The str.rpartition() method splits the string at the last occurrence of the provided separator.

main.py
my_str = 'bobbyhadz.com/articles/python' result = my_str.rpartition('/')[2] print(result) # ๐Ÿ‘‰๏ธ 'python' # ๐Ÿ‘‡๏ธ ('bobbyhadz.com/articles', '/', 'python') print(my_str.rpartition('/'))

The method returns a tuple containing 3 elements - the part before the separator, the separator, and the part after the separator.

If the separator is not found in the string, the method returns a tuple containing two empty strings, followed by the string itself.
main.py
my_str = 'bobby-hadz-com' # ๐Ÿ‘‡๏ธ ('', '', 'bobby-hadz-com') print(my_str.rpartition('!'))

Accessing the tuple at an index of -1 would return the entire string if the separator is not contained in the string.

main.py
my_str = 'bobby-hadz-com' result = my_str.rpartition('1')[-1] print(result) # ๐Ÿ‘‰๏ธ bobby-hadz-com
The code for this article is available on GitHub

I've also written an article on how to split a string and remove the whitespace.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev