[英]How to find substring in a targeted string more accurately in python?
[英]How to find the last targeted string in a string by Python?
我們都知道如何在字符串中找到第一個目標字符串。
string.index('abc')
因此,這段代碼將幫助我找到“ abc”出現在字符串中的第一個位置。
但是,我想知道如何找到最后一個“ abc”位置。
我已經想出一種算法,但這很愚蠢。
1. reverse whole string and 'abc'.
2. temp_Location = string.index('cba')
3. exactly_Location = len(string) - temp_Location - len('cba')
我知道這真的很愚蠢...有人可以告訴我如何聰明地做嗎?
非常感謝。 :)
s = 'abcabc'
s.rindex('abc') # evaluates to 3
您還可以使用Python regex庫 ,如果需要,它將提供更多功能。
就您而言,您可以簡單地執行以下操作:
import re
s = 'abcabc'
[i.start() for i in re.finditer('abc', s)][-1] #last index from all match indices
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.