[Python] Anyone can explain ord(c)&31?

At the end of a “short” challenge, I came up with my shortest code… Part of it was :
ord©-96for c in input().lower()
Praveend came up with a shorter solution that I don’t understand :
ord©&31for c in input()
Anyone can explains it to me ?

Swann

In Python (and other languages) the operators & (and), | (or), ^ (xor), ~ (not) act bitwise on integers. For example,

ord('D') & 31 ->  68 & 31 ->  100100 (binary) & 11111 (binary) -> 00100 (binary) -> 4
ord('d') & 31 -> 100 & 31 -> 1100100 (binary) & 11111 (binary) -> 00100 (binary) -> 4

In this case, &31 is equivalent to %32 which may be a more readable alternative. Of course, this works because of the positions of ‘a’, ‘b’, … and ‘A’, ‘B’, … in the ASCII table.

Another useful trick: x ^ 1 is equivalent to 2 * (x // 2) + (x % 2). For example, 5 ^ 1 == 4 and 4 ^ 1 == 5.

For more about bitwise operators in Python see here.

3 Likes