Python | First character occurrence from rear String
Last Updated :
15 Mar, 2023
There are many ways to find out the first index of element in String as python in its language provides index() function that returns the index of first occurrence of element in String. But if one desires to get the last occurrence of element in string, usually a longer method has to be applied. Lets discuss certain shorthands to achieve this particular task.
Method #1 : Using rfind() This is usually the hack that we can employ to achieve this task. Employing string function rfind() to get the first element from right i.e last index of element in String.
Python3
# Python 3 code to demonstrate
# First character occurrence from rear String
# using rfind()
# initializing string
test_str = "Geeksforgeeks"
# printing original string
print ("The original string is : " + str(test_str))
# using rfind()
# to get last element occurrence
res = test_str.rfind('e')
# printing result
print ("The index of last element occurrence: " + str(res))
Output : The original string is : Geeksforgeeks
The index of last element occurrence: 10
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(1).
Method #2 : Using List Slice + index() + list() One can convert the string to list using list() and then using list slicing we reverse the list and use the conventional index method to get the index of first occurrence of element. Due to reversed list, the last occurrence is returned rather than the first index of list.
Python3
# Python 3 code to demonstrate
# First character occurrence from rear String
# using List Slice + index() + list()
# initializing string
test_str = "Geeksforgeeks"
# printing original string
print ("The original string is : " + str(test_str))
# using List Slice + index() + list()
# First character occurrence from rear String
test_str = list(test_str)
res = len(test_str) - 1 - test_str[::-1].index('e')
# printing result
print ("The index of last element occurrence: " + str(res))
Output : The original string is : Geeksforgeeks
The index of last element occurrence: 10
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using max() method
Python3
# Python 3 code to demonstrate
# First character occurrence from rear String
# initializing string
test_str = "Geeksforgeeks"
# printing original string
print ("The original string is : " + str(test_str))
# First character occurrence from rear String
x=[]
for i in range(0,len(test_str)):
if(test_str[i]=="e"):
x.append(i)
res=max(x)
# printing result
print ("The index of last element occurrence: " + str(res))
OutputThe original string is : Geeksforgeeks
The index of last element occurrence: 10
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(m), where m is the number of occurrences of the character "e" in the input string.
Method #4: Using index() method
Python3
# Python 3 code to demonstrate
# First character occurrence from rear String
# using index
# initializing string
test_str = "Geeksforgeeks"
# Reversing the string
reverse_str = test_str[::-1]
# printing original string
print("The original string is : " + str(test_str))
# using index()
# to get last element occurrence
res = reverse_str.index('e')
res = len(test_str)-res - 1
# printing result
print("The index of last element occurrence: " + str(res))
OutputThe original string is : Geeksforgeeks
The index of last element occurrence: 10
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #5: Python code to demonstrate First character occurrence from rear String using Regex
Python3
import re
#initializing string
test_str = "Geeksforgeeks"
#printing original string
print("The original string is : " + str(test_str))
#using Regex to get last element occurrence
match = re.search(r'e(?!.*e)', test_str)
res = match.start()
#printing result
print("The index of last element occurrence: " + str(res))
OutputThe original string is : Geeksforgeeks
The index of last element occurrence: 10
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #6: Using a loop to iterate through the string from the end
Start iterating through the string from the end using a loop. Check each character and if we find the first occurrence of the character we're looking for, store the index and break out of the loop.
Python3
#initializing string
test_str = "Geeksforgeeks"
#printing original string
print("The original string is : " + str(test_str))
#iterating through the string from the end
for i in range(len(test_str)-1, -1, -1):
if test_str[i] == 'e':
res = i
break
#printing result
print("The index of last element occurrence: " + str(res))
OutputThe original string is : Geeksforgeeks
The index of last element occurrence: 10
Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(1).
Similar Reads
Python - Characters Index occurrences in String
Sometimes, while working with Python Strings, we can have a problem in which we need to check for all the characters indices. The position where they occur. This kind of application can come in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using set() + reg
6 min read
Python | Return lowercase characters from given string
Sometimes, while working with strings, we are concerned about the case sensitivity of strings and might require getting just a specific case of character in a long string. Let's discuss certain ways in which only lowercase letters can be extracted from a string. Method #1: Using list comprehension +
5 min read
Python | Lowercase first character of String
The problem of capitalizing a string is quite common and has been discussed many times. But sometimes, we might have a problem like this in which we need to convert the first character of the string to lowercase. Let us discuss certain ways in which this can be performed. Method #1: Using string sli
4 min read
Python - Replace occurrences by K except first character
Given a String, the task is to write a Python program to replace occurrences by K of character at 1st index, except at 1st index. Examples: Input : test_str = 'geeksforgeeksforgeeks', K = '@' Output : geeksfor@eeksfor@eeks Explanation : All occurrences of g are converted to @ except 0th index. Input
5 min read
Python - Extract range characters from String
Given a String, extract characters only which lie between given letters. Input : test_str = 'geekforgeeks is best', strt, end = "g", "s" Output : gkorgksiss Explanation : All characters after g and before s are retained. Input : test_str = 'geekforgeeks is best', strt, end = "g", "r" Output : gkorgk
4 min read
Python - Extract String till all occurrence of characters from other string
Given a string, the task is to write a Python program to extract till all characters from other strings are found. Input : test_str = "geeksforgeeks is best for all geeks", check_str = "freak"Output : geeksforgeeks is best for aExplanation : a is last letter in freak to be present in string. The str
11 min read
Python - Extract String after Nth occurrence of K character
Given a String, extract the string after Nth occurrence of a character. Input : test_str = 'geekforgeeks', K = "e", N = 2 Output : kforgeeks Explanation : After 2nd occur. of "e" string is extracted. Input : test_str = 'geekforgeeks', K = "e", N = 4 Output : ks Explanation : After 4th occur. of "e"
7 min read
Python - Group list by first character of string
Sometimes, we have a use case in which we need to perform the grouping of strings by various factors, like first letter or any other factor. These types of problems are typical to database queries and hence can occur in web development while programming. This article focuses on one such grouping by
7 min read
Python - Remove Rear K characters from String List
Sometimes, we come across an issue in which we require to delete the last characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plu
5 min read
Python | Substitute character with its occurrence
Sometimes, while working with Python, we can have a problem in which we need to substitute a character with its occurrence in a string. This a peculiar problem but can have application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop This is brut
6 min read