[英]Finding nth position of substring in a string using python
讓我們以字符串為例,'我是程序員,我正在編寫代碼。 我對它感興趣',目標詞(子字符串)是'am'。 我想通過完整的單詞而不是索引找到它的第 n 個值。 例如,substring 'am' 位於第 2、第 6 和第 10 position。 我嘗試搜索,但所有結果都與查找索引有關。 我發現第 n 個值對我不起作用。 代碼在 'IF' 的 ':' 上給出錯誤。
parts= haystack.split(needle, n+1)
if len(parts)<=n+1:
return -1
return len(haystack)-len(parts[-1])-len(needle)
您對此有最佳且簡單的解決方案嗎? 我試圖用可能的解決方案和邏輯來解決問題。 您的合作將不勝感激。
你可以做這樣的事情。
string = 'I am programmer and I am doing coding. I am interested in it'.split()
target = 'am'
for count,words in enumerate(string):
if words == target:
print(count)
這會給你1,5,9
。 這是因為索引從零開始。 現在,當然,如果您想要 2、6、10,您可以在打印時添加一個來計數。
列表理解
string = 'I am programmer and I am doing coding. I am interested in it'.split()
target = 'am'
wordPlace = [count for count,words in enumerate(string) if words == target]
我嘗試了以下代碼,它在下面調用 function 的字符串上工作。
counter=0
lst=[]
if target in string:
li=list(string.split(" ")) #li is list, string to list
j = [i for i, x in enumerate(li) if x == "exam"]
print("Positions of string ",target," is :-")
for s in range(len(j)):
print(j[s]+1)
else:
return "Target word not in the string."
print(findTargetWord("Today is my exam and exam is easy", "exam")) #it worked on this string
我試過字符串今天是我的期末考試。 我沒有為考試做好充分的准備。 我不知道,我將在考試中表現如何。 它沒有返回正確答案,而是打印21 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.