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

2024-05-23 15:49:46 发布

您现在位置:Python中文网/ 问答频道 /正文

让我们以字符串为例,'我是程序员,我在做编码。“我对它感兴趣”,目标词(子字符串)是“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)

你有一个最简单的解决方案吗。我试图用可能的解决方案和逻辑来解决这个问题。非常感谢您的合作


Tags: 字符串代码目标编码lenreturn解决方案am
2条回答

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

    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

你可以这样做

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]

相关问题 更多 >