Search code examples
pythonalgorithmif-statementcode-readability

Shorten an if statement whose statement are reversed


I have the following situation:

string = "abc"
if (string[1] == "b" and string[2] == "c") or (string[1] == "c" and string[2] == "b"):
    print("ERROR")

Is there a solution to shorten this in a pythonic way? I see that (string[1] == "b" and string[2] == "c") is the reverse statement of (string[1] == "c" and string[2] == "b"). Maybe I can use that?


Solution

  • Is there a solution to shorten this in a pythonic way?

    Yes, here it is:

    string = "abc"
    if (string[1:3] == "bc") or (string[1:3] == "cb"):
        print("ERROR")
    

    If eagering for a more short way - if string[1:3] in ('bc', 'cb'):