Search code examples
pythonwhile-loopinfinite-loop

Python replacing substring with a loop


I am taking some arbitrary expression like 6 ++++6, or 6+---+++9++5 and need to parse it into its simplest form (so eg 6+6 and 6-9+5) Why does the following code result in an infinite loop? From debugging I can see that the string is being successfully updated, but it's like the condition is not being reevaluated.

while "--" or "+-" or "-+" or "++" in user_input:
        user_input = user_input.replace("--", "+")
        user_input = user_input.replace("+-", "-")
        user_input = user_input.replace("-+", "-")
        user_input = user_input.replace("++", "+")

Solution

  • You can make use of any, to create a well defined break-condition for your while loop:

    replacements = [
        ("--", "+"),
        ("+-", "-"),
        ("-+", "-"),
        ("++", "+")
    ]
    
    user_input = '6+---+++9++5'
    while any(pattern[0] in user_input for pattern in replacements):
        for pattern in replacements:
            user_input = user_input.replace(*pattern)
    print(user_input)
    

    Out:

    6-9+5