find and replace with multiple for loops in Python
Question: I want to update a text file so that all consecutive capital letters have a
space between them. My approach was to use two `for` loops while reading the
file line by line.

    
    
    import sys, fileinput
    
    ActiveFileR = open('text.txt', 'r')
    ActiveFileW = open('textW.txt', 'w')
    
    CapAlphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    
    for line in ActiveFileR:
        for ReChr1 in CapAlphabet:
            for ReChr2 in CapAlphabet:
                ActiveFileW.write(line.replace(ReChr1 + ReChr2, ReChr1 + " " + ReChr2))
    

However, this resulted in 676 (26*26) lines in the output file for each line
in the input file. I understand why this happened but do not know how to
correct it. I want to keep looping the same line until all spaces have been
added before moving on to the next line.


Answer: Just modify the line in a local variable, and only write it out once:

    
    
    for line in ActiveFileR:
        newline = line
        for ReChr1 in CapAlphabet:
            for ReChr2 in CapAlphabet:
                newline = newline.replace(ReChr1 + ReChr2, ReChr1 + " " + ReChr2)
        ActiveFileW.write(newline)
    

