2

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?

Larsus
  • 101
  • 1
  • 12
  • 1
    `string[1] == "b" and string[2] == "c"` isn't the reverse statement of `string[1] == "c" and string[2] == "b"`. This is `!(string[1] == "b" and string[2] == "c")` or `string[1] != "b" OR string[2] != "c"` – Cid Oct 11 '19 at 12:53
  • 2
    Are the indices important, or do you actually want to check if the substr "bc" or "cb" exists inside `string` ? – Wololo Oct 11 '19 at 12:54
  • @Cid Sorry, I mean only "b" and "c" are swapped – Larsus Oct 11 '19 at 12:55
  • @magnus question is important concerning your problem – Cid Oct 11 '19 at 12:56
  • @magnus I want to check if the substring "bc" or "cb" exists inside the string. But they have to be the second an third letter – Larsus Oct 11 '19 at 12:58
  • @Cid I don't understand your comment? I'm not the OP. – Wololo Oct 11 '19 at 13:06
  • @magnus I know, I'm telling OP that your question is relevant – Cid Oct 11 '19 at 13:36

1 Answers1

6

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'):

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • Might add that if the pattern is arbitrary and stored in a variable named, say `pattern="bc"`, it may be reversed by `pattern[::-1]` to obtain "cb" – Wololo Oct 11 '19 at 13:03