根据 python 中字符串的不同出现次数插入一个字符串

Insert a string based on differing occurence counts of strings in python

我希望有人能帮助我解决以下问题。

假设我有以下文本(更精确 - 来自乳胶 table 的代码块)。

接下来,我想根据两个输入因素将字符串放在文本内部,在文本内部,一个基于 \ 指定行,另一个基于 & 指定列。

所以在 (1,1) 对的情况下,字符串应该放在第一次出现的 \ 和第一次出现的 & 之前。 (1, 1, “HERE”, text) 作为输入应该 return:

并且对于 (2, 2, “HERE”, text) 应该 return

理想情况下,该函数还需要多对输入,因此输入 1,1 和 2,2:

应该是结果。

我目前的方法没有将 & 和 \ 区别对待。 而HERE并没有出现在前面。


text = "Some & random & content \ Some & further & content \ …. "

def replacenth(string, sub, wanted, n):
    pattern = re.compile(sub)
    where = [m for m in pattern.finditer(string)][n-1]
    before = string[:where.start()]
    after = string[where.start():]
    newString = before + wanted + after
    return newString

replacenth(text, "[&\+]", "HERE" , 2)

#output: 
#'Some & random HERE& content \ Some & further & content \ …. '

也许是这样的。使用 str.split and str.join。虽然没有检查错误输入。

def replace(string, sub, row_col_pairs):
    rows = string.split(' \ ')
    for row, col in row_col_pairs:
        cells = rows[row-1].split(' & ')
        cells[col-1] = sub+cells[col-1]
        rows[row-1] = ' & '.join(cells)
    return ' \ '.join(rows)

replace(text, "HERE", [(1, 3), (2, 2)])

# output
# Some & random & HEREcontent \ Some & HEREfurther & content \ ….