2

Playing around with isalpha(), I have noticed some strange behaviour.

"a".isalpha()
>>True
"2".isalpha()
>> False

The two statements above, return what I would expect them to. However, now adding a tilde before, makes less sense.

~"a".isalpha()
>> -2
~"2".isalpha()
>> -1

Why does this happen? I have discovered that using not instead of ~ returns the output I was expecting, but am interested in the behaviour above.

not "a".isalpha()
>> False
not "2".isalpha()
>> True
OD1995
  • 1,647
  • 4
  • 22
  • 52

1 Answers1

5

From the python documentation on bitwise operators (emphasis mine):

~ x: Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.

Since in python True == 1 and False == 0, ~True == -1 - 1 == -2 and ~False == -0 - 1 == -1.

As you discovered, to do what you want to do (logical inverse), you need to use the not operator.

glibdud
  • 7,550
  • 4
  • 27
  • 37