我想在给定的输入字符串str中找到某个子字符串的最后一次出现的位置(或索引)。

例如,假设输入字符串是str = 'hello',子字符串是target = 'l',那么它应该输出3。

我该怎么做呢?


当前回答

# Last Occurrence of a Character in a String without using inbuilt functions
str = input("Enter a string : ")
char = input("Enter a character to serach in string : ")
flag = 0
count = 0
for i in range(len(str)):
    if str[i] == char:
        flag = i
if flag == 0:
    print("Entered character ",char," is not present in string")
else:
    print("Character ",char," last occurred at index : ",flag)

其他回答

使用str.rindex方法。

>>> 'hello'.rindex('l')
3
>>> 'hello'.index('l')
2

使用.rfind ():

>>> s = 'hello'
>>> s.rfind('l')
3

另外,不要使用str作为变量名,否则会影响内置的str()。

# Last Occurrence of a Character in a String without using inbuilt functions
str = input("Enter a string : ")
char = input("Enter a character to serach in string : ")
flag = 0
count = 0
for i in range(len(str)):
    if str[i] == char:
        flag = i
if flag == 0:
    print("Entered character ",char," is not present in string")
else:
    print("Character ",char," last occurred at index : ",flag)

您可以使用rindex()函数来获取字符串中字符的最后一次出现

s="hellloooloo"
b='l'
print(s.rindex(b))

如果你不想使用rfind,那么这个可以使用/

def find_last(s, t):
    last_pos = -1
    while True:
        pos = s.find(t, last_pos + 1)
        if pos == -1:
            return last_pos
        else:
            last_pos = pos