[英]How to find the index of the last character of a substring in python
如何在 python 中找到 substring 的最后一個字符的索引 例如:s = "hello"
s.find("he") 中最后一個字符 'e' 的索引
if substr in s:
idx = s.find(substr) + len(substr) - 1
print(s[idx])
在你的情況下 substr = 'he'
s.find() 返回 substring 的第一個符號的索引。 您需要添加 len(substr) - 1 以獲取 substring 的最后一個符號的索引
您可以通過以下方式簡單地做到這一點 -
string = "hello"
subStr = "he"
if (string.find(subStr) != -1):
print(string[string.find(subStr)+len(subStr)-1])
else:
print("Substring not found")
這是應該做的
def get_index(s,substring):
start = s.find(substring)
if(start != -1):
return start + len(substring) - 1
else:
print("substring not found")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.