Search code examples
python-3.xstringimmutabilitystr-replace

How do I retain a new strings value during a loop, continuously changing the string until the loop ends?


I want to take the value of a string and loop, asking the user to choose single character replacement during each loop iteration. I want to retain the changes the user makes to the string and then make an additional replacement which is also retained until the user chooses to end the loop.

newtext = ''
ciphertext = 'qsv el arm aepm sh tzz ussx pmb as dspm as arm tex sh armel dsvbaci.'
answer = 'y'

for letter in ciphertext:
    while answer is 'y':
        print(ciphertext)
        cl = input('Which letter would you like to replace? ')
        rl = input('What is the new letter? ')
        newtext += ciphertext.replace(cl,rl)
        print(newtext)
        answer = input('Would you like to continue? (y/n) ')

Solution

  • I think you should do like this:

    original = 'qsv el arm aepm sh tzz ussx pmb as dspm as arm tex sh armel dsvbaci.'
    ciphertext = 'qsv el arm aepm sh tzz ussx pmb as dspm as arm tex sh armel dsvbaci.'
    newtext = ''
    answer = 'y'
    
    
    while answer is 'y':
        print(ciphertext)
        cl = raw_input('Which letter would you like to replace? ')
        rl = raw_input('What is the new letter? ')
        newtext = ciphertext.replace(cl,rl)
        print(newtext)
        answer = raw_input('Would you like to continue? (y/n) ')
        if(answer == "y"):
            ciphertext = newtext
        else:
            ciphertext = original
    

    I changed a little bit your code. If you need any clarification lemme know

    UPDATE

    original = 'qsv el arm aepm sh tzz ussx pmb as dspm as arm tex sh armel dsvbaci.'
    plaintext = 'qsv el arm aepm sh tzz ussx pmb as dspm as arm tex sh armel dsvbaci.'
    answer = 'y'
    replacements = {}
    
    
    while answer is not 'q':
        print(plaintext)
        cl = input('Which letter would you like to replace? ')
        rl = input('What is the new letter? ')
        x = [i for i, ltr in enumerate(original) if ltr == cl]
        replacements[cl] = x
        plaintext = list(plaintext)
        for i in replacements[cl]:
            plaintext[i] = rl
        plaintext = "".join(plaintext)
        print plaintext
        answer = input('Would you like to continue? (y/n) ')
        if(answer == "n"):
            plaintext = original
    

    This should be good! Lemme know. I'm aware about the raw_input problem, i changed to input for a faster "debugging". Sorry but i didn't understand before the problem correctly :P