iKyriaki
iKyriaki

Reputation: 609

Having trouble translating strings

I've decided to start on a project over spring break, taking characters from a webcomic and translating text as if that character was saying it. I've managed to get it to work well for one character, but there's a slight problem.

def meulin():
    replace = {'EE':'33', 'ee':'33'}
    originalText = input('Input text -> ')
    while True:
        for i, j in replace.items():
            if i in originalText:
                newText = originalText.replace(i,j)
                print(newText.upper())
            else:
                print(originalText.upper())
        originalText = input('Input text (type "quit" to end program.) -> ')
        if originalText in ('quit', 'end', 'exit', 'stop', 'q'):
            sys.exit('Program ended.')

When I ran PyScripter's debugger, it told me that after getting input, the program starts at the for i, j in replace.items(): line, skips the if statement completely and goes to the else statement, then goes to the if statement. So instead of just posting

CH33SE

it'll post

CHEESE

CH33SE

I could just remove the else statement completely, but then it wouldn't post the original text at all. Any suggestions would be appreciated.

Upvotes: 0

Views: 63

Answers (1)

dsh
dsh

Reputation: 12214

for i, j in replace.items():
    if i in originalText:
        newText = originalText.replace(i,j)
        print(newText.upper())
        break
else:
    print(originalText.upper())

The break statement means the loop will stop after the first substitution. Python allows an else clause on a for loop which will execute only if the loop is not stopped by a break statement.

The reason you saw the output twice is because you have two items in your dict. I think you are looking to print the original text only when none of the substitutions match.

Upvotes: 1

Related Questions