Get substring from index to end of string in Python

avatar

Borislav Hadzhiev

Last updated: Sep 6, 2022

banner

Photo from Unsplash

Get substring from index to end of string in Python #

Use string slicing to get the substring from an index to the end of a string, e.g. result = my_str[index:]. When the value for the stop index is not specified, the slice goes to the end of the string.

main.py
my_str = 'bobbyhadz' # 👇️ get index of first occurrence of character index = my_str.index('h') result = my_str[index:] print(result) # 👉️ 'hadz' # ------------------------------------ # 👇️ get index of last occurrence of character last_index = my_str.rindex('b') print(my_str[last_index:]) # 👉️ 'byhadz'

We used string slicing to get the substring from an index to the end of the string.

The syntax for string slicing is my_str[start:stop:step].

The start index is inclusive, whereas the stop index is exclusive (up to, but not including).

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(my_str) - 1.

We can get a slice to the end of the string by omitting the stop index.

main.py
my_str = 'bobbyhadz' index = my_str.index('h') result = my_str[index:] print(result) # 👉️ 'hadz'

The value for the stop index is exclusive (up to, but not including), so if you specify an index of -1, the last character in the string won't be included in the slice.

main.py
my_str = 'bobbyhadz' index = my_str.index('h') result = my_str[index:-1] print(result) # 👉️ 'had'

The slice goes up to, but not including the last character in the string.

The str.index method returns the index of the first occurrence of the provided substring in the string.

The method raises a ValueError if the substring is not found in the string.

You can use a try/except block to handle the scenario where the substring is not found in the string.

main.py
my_str = 'bobbyhadz' try: index = my_str.index('X') result = my_str[index:] print(result) except ValueError: # 👇️ this runs print('The substring is not contained in the string')

The except block handles the ValueError if the substring is not contained in the string.

The str.index() method returns the index of the first occurrence of the given substring in the string.

If you need to get the index of the last occurrence, use the str.rindex() method.

main.py
my_str = 'bobbyhadz' last_index = my_str.rindex('b') print(my_str[last_index:]) # 👉️ 'byhadz'

The str.rindex method returns the highest index in the string where the provided substring is found.

The rindex() method also raises a ValueError if the substring is not contained in the string.

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.