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

时间:2019-06-20 15:59:23

标签: python arrays

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

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

有人可以帮助我吗?请!谢谢!

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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 ']

这是你的追求吗?