Skip to main content
 首页 » 编程设计

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

2025年05月04日21Terrylee

我想将数组中的搜索文本从指定元素替换为该数组中的另一个指定元素。 我知道有一个“替换”功能,但它会替换该搜索字段的所有匹配项。所以我想知道是否有其他功能或其他技巧可以做我想做的事 像这样:

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 

谁能帮帮我?请!谢谢!

请您参考如下方法:

您可以查找 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 ']