Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python查找字符串中子字符串的第n个位置_Python_String_Substring - Fatal编程技术网

使用python查找字符串中子字符串的第n个位置

使用python查找字符串中子字符串的第n个位置,python,string,substring,Python,String,Substring,让我们以字符串为例,'我是程序员,我在做编码。“我对它感兴趣”,目标词(子字符串)是“am”。我想找到它的第n个值,它是由完整的单词,而不是索引确定的。例如,子字符串“am”位于第2、第6和第10位置。 我尝试了搜索,但所有结果都与查找索引相关。我发现一个关于n的值对我不起作用。代码在“IF”的“:”上出错 parts= haystack.split(needle, n+1) if len(parts)<=n+1: return -1 return

让我们以字符串为例,'我是程序员,我在做编码。“我对它感兴趣”,目标词(子字符串)是“am”。我想找到它的第n个值,它是由完整的单词,而不是索引确定的。例如,子字符串“am”位于第2、第6和第10位置。 我尝试了搜索,但所有结果都与查找索引相关。我发现一个关于n的值对我不起作用。代码在“IF”的“:”上出错

    parts= haystack.split(needle, n+1)
    if len(parts)<=n+1:
        return -1
    return len(haystack)-len(parts[-1])-len(needle)
parts=haystack.split(针,n+1)

如果len(parts)你可以这样做

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]

我尝试了下面的代码,它在下面调用函数的字符串上工作

    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

,所以您只想匹配整个单词,对吗?否则“程序员”将匹配“am”。这是否回答了您的问题?(其中列表是haystack.split(“”)的结果)@TomKarzes Yes。简言之,我想根据第n个位置上的单词找到整个单词的位置。这能回答你的问题吗@我使用您共享的链接尝试了以下代码/bin/python3 def FindNthTargetString(string,target):counter=0 lst=[]如果string中的target:li=list(string.split(“”)j=[i代表i,x代表枚举中的x(li)如果x==target]print(“string的位置”,目标,“is:-”)对于范围中的s(len(j)):print(j[s]+1)否则:返回“目标字不在字符串中”这个字符串很好用,不是因为“今天是我的期中考试。我还没有完全准备好考试。我不知道,我会在考试中表现如何。”谢谢你的回答。上面的代码,它返回了我22和字符串今天是我的会期考试。我没有为考试做好充分的准备。我不知道,我将如何在考试和寻找目标词考试中表现。所需的输出是上面提到的这个字符串的4、11和20。它工作了吗?