replacing '-' with a list of characters from another files keeping the position fixed using python

I try to replace '-' in file1 (contains many lines) with characters (in the same position as '-' in file 1) from file2. Here is the example;

Inputs

file1:

-------V--------------------
----------------N----------I

file2:
FLDGIDKAQEEHEKYHSNWRAMASDFNL

desire outputs:
FLDGIDKVQEEHEKYHSNWRAMASDFNL
FLDGIDKAQEEHEKYHNNWRAMASDFNI

Now I tried these type of code:


f1=open("file1").read()
f2=open("file2").read()

#replace '-' with the character from file2
def replace(index_list,character,string):
    string=list(string)

    for index in index_list:
        string[index]=character
    return "".join(string)

#print the positions in file1 where '-' is there

for line in f1: 
    for i in range(0, len(line)): 
        if line[i]== '-': 
        p=i+1 
        print(replace(p,f2[p],f1))

the positions (p) are printing fine but I'm not able to replace them properly. Could anyone please help me with the code or some other options? It will be really helpful. Thank you very much.


Solution 1:

Use slices to replace the corresponding characters. In the following code, I use enumerate() to get the index of the character in the string with replacements (i) and the character (c). Then, if the character is not a hyphen, you just have to get the substring to the left of the index (new_line[:i]) plus the character plus the substring to the right of the index without the character at said position (new_line[i+1:]).

The advantage of using slices is that you don't have to worry about the indices falling out of range. For instance, if the character to replace is at the end of the string (as in the second replacement pattern), new_line[i+1] results in an empty string because i will be greater than the last index in the string.

from pathlib import Path

file1 = Path('file1.txt')
file2 = Path('file2.txt')

with file1.open('r') as f1, file2.open('r') as f2:
    f1_lines = f1.read().splitlines()
    f2_lines = f2.read().splitlines()

    for line_2 in f2_lines:
        for line_1 in f1_lines:
            new_line = line_2
            for i, c in enumerate(line_1):
                if c != '-':
                    new_line = new_line[:i] + c + new_line[i+1:]
            print(new_line)