Python:索引子字符串中的位置

标签 python

我正在尝试创建一个程序,该程序将列出子字符串在父字符串中出现的位置。例如,假设我们在父字符串“abcabcabcabcabcabca”中搜索“bc”,程序将返回 1、4、7、10、13、16。

到目前为止,我一直在使用:

import string

def subStringMatchExact():
    print "This program will index the locations a given sequence"
    print "occurs within a larger sequence"
    seq = raw_input("Please input a sequence to search within: ")
    sub = raw_input("Please input a sequence to search for: ")
    n = 0
    for i in seq:
        x = string.find(seq, sub [n:])
        print x
        n = x + 1

我还尝试用 string.index 运算符替换 string.find。任何建议将不胜感激。

最佳答案

只需调用 .find()在输入字符串本身上。如果未找到匹配项,它将返回匹配项的位置或 -1。它还需要一个start 参数,因此您可以查找下一个 匹配项:

def subStringMatchExact():
    print "This program will index the locations a given sequence"
    print "occurs within a larger sequence"
    seq = raw_input("Please input a sequence to search within: ")
    sub = raw_input("Please input a sequence to search for: ")

    positions = []
    pos = -1
    while True:
        pos = seq.find(sub, pos + 1)  # start searching *beyond* the previous match
        if pos == -1:   # Not found
            break
        positions.append(pos)
    return positions

关于Python:索引子字符串中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15056856/

相关文章:

python - 如何检查 conda develop 是否安装了我的项目/包?

python - numpy `arange` 超过最终值

python - Python 中的定点迭代

python - 将列值更改为 Pandas 中的列标题

python - macOS BigSur 上 python 版本的问题

python - 快速 Numpy 循环

python - 如何强制 virtualenv 从 pypi 安装最新的 setuptools 和 pip?

python - 在 Python 中声明简单 PyParsing 递归语法的奇怪警告

python - 操作错误 : no such column: XX - Sqlite

python - 如何以表格形式和字母顺序打印字典?