Get the index of the last occurrence of a substring in Python: Search a word from right to left
How can we get the index of the last occurrence of a substring in Python? google
has two g
and the index of the last g
is 3.
s = 'google'
x = s.rfind('g')
y = s.index('g')
z = s.find('g')
print(x) # 3
print(y) # 0
print(z) # 0
The rfind()
returns the index of the last occurrence of a substring in Python. The find()
returns the index of the substring found first so s.find('g')
is 0. The find()
and index()
are almost the same and this post explains the difference.
The name of rfind
means "right find". The rfind()
searches the substring from the right to the left.
Python String
- Check if a string contains the other string
- Check if a string starts with another string
- Split a string
- Concatenate strings
- Get the index of substring
- Get the index of the last occurrence of a substring
- Trim a string
- Replace a substring
- Replace multiple spaces with one space
- Fill 0 letters to a string
- Capitalize a string
- Convert a string lowercase
- Check if a string is numeric
- Check if a string is uppercase
- Parse a string to a float
- Format a string
- f-string
- Reverse a string
- Slice a string
- Subtract a string from another string
- Make a random string
- Generate a secure token
- Encode a string
- Get the sha256 value
- Convert an integer to a hexadecimal string
- Get a character or integer value
- Get digits or ASCII letters
- Center a string
- Convert string to tuple