1

This is my attempt at understanding what it does:

>>> ~
SyntaxError: invalid syntax
>>> print ~
SyntaxError: invalid syntax
>>> ~ = cheese
SyntaxError: invalid syntax
>>> ~ = "21"
SyntaxError: invalid syntax
>>> 2 ~ 1
SyntaxError: invalid syntax
>>> ~ = "w"
SyntaxError: invalid syntax
>>> a = "w"
>>> a
'w'
>>> print ~8
-9
>>> print ~w

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    print ~w
NameError: name 'w' is not defined
>>> print ~"w"

It seems to only work with numbers, so an explanation and a link to some documentation would be very helpful.

Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • [Googlemedo](http://stackoverflow.com/questions/8305199/the-tilde-operator-in-python) – RickyA Sep 11 '13 at 13:10
  • I thought it was called a tridle – Games Brainiac Sep 11 '13 at 13:10
  • I have it on [good authority](http://www.catb.org/jargon/html/T/twiddle.html) that it is pronounced "twiddle". On the [other hand](https://en.wikipedia.org/wiki/INTERCAL#Operators) it might be pronounced "select". – msw Sep 11 '13 at 13:17
  • For the love of what you think is good, could you stop it with the down votes? I get it already. – Games Brainiac Sep 11 '13 at 14:02

1 Answers1

7

~ is a unary operator (i.e. it takes only one argument) which calculates the bitwise inverse of its argument. The result is -x - 1, because in Two's complement representation, -x is the same as inverting all bits and then adding one.

phihag
  • 278,196
  • 72
  • 453
  • 469