将指定的文本从索引替换为数组python中的另一个索引

2024-04-25 22:27:14 发布

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

我要将数组中的搜索文本从指定元素替换为此数组中的另一个指定元素。 我知道有一个“replace”函数,但它将替换搜索到的所有字段。所以我想知道是否有另一个功能或另一个技巧,可以做我想要的 像这样:

myarray = ["time (1)",
"the text to replace ",
"time (2)",
"the text to replace ",
"time (3)",
"the text to replace ",
"time (4)",
"the text to replace ",
"time (5)",
"the text to replace ",
"time (6)",
"the text to replace ",
"time (7)",
"the text to replace ",
"time (8)",
"the text to replace ",
"time (9)",
"the text to replace ",
"time (10)",
"the text to replace "]

myfunc(4,8)

def myfunc(fromtime, totime):
    for line in myarray
    #find the time from (fromtime) to (totime) and replace 'text' with 'string' for example
    print myarray

有人能帮我吗?拜托!谢谢您!你知道吗


Tags: theto函数text文本功能元素for
2条回答

假设myarray具有给定的格式,您可以编写如下内容:

def myfunc (fromtime, totime):
    i = fromtime*2 - 1
    while i <= (totime*2 - 1):
        myarray[i] = myarray[i].replace('text', 'string')
        i+=2

myfunc(4, 8)的输出是:

['time (1)',
 'the text to replace ',
 'time (2)',
 'the text to replace ',
 'time (3)',
 'the text to replace ',
 'time (4)',
 'the string to replace ',
 'time (5)',
 'the string to replace ',
 'time (6)',
 'the string to replace ',
 'time (7)',
 'the string to replace ',
 'time (8)',
 'the string to replace ',
 'time (9)',
 'the text to replace ',
 'time (10)',
 'the text to replace ']

这就是你要找的吗?你知道吗

您可以查找time (4)time(8)的索引,但是使用其中的myarray.index()对包含在这些限制中的字符串进行更改

myarray = ["time (1)","the text to replace ","time (2)","the text to replace ","time (3)","the text to replace ","time (4)","the text to replace ","time (5)","the text to replace ","time (6)","the text to replace ","time (7)","the text to replace ","time (8)","the text to replace ","time (9)","the text to replace ","time (10)","the text to replace "] 

def myfunc(myarray, fromtime, totime):
    original_string , replace_string = 'text', 'string'
    start_index = myarray.index("time ({})".format(fromtime))
    end_index = myarray.index("time ({})".format(totime)) + 2 # + 2 because you want to also change value for the outbound limit
    myarray[start_index : end_index] = [value if idx%2 == 0 else value.replace(original_string, replace_string) for idx, value in enumerate(myarray[start_index : end_index]) ]
    return myarray

myfunc(myarray, 4,8)

输出

['time (1)',
 'the text to replace ',
 'time (2)',
 'the text to replace ',
 'time (3)',
 'the text to replace ',
 'time (4)',
 'the string to replace ',
 'time (5)',
 'the string to replace ',
 'time (6)',
 'the string to replace ',
 'time (7)',
 'the string to replace ',
 'time (8)',
 'the string to replace ',
 'time (9)',
 'the text to replace ',
 'time (10)',
 'the text to replace ']

相关问题 更多 >