【问题标题】:What does the ~ operator do in Python [duplicate]〜运算符在Python中做了什么[重复]
【发布时间】:2013-09-15 12:43:26
【问题描述】:

这是我试图理解它的作用:

>>> ~
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"

它似乎只适用于数字,所以解释和一些文档的链接会很有帮助。

【问题讨论】:

  • 我以为这叫三轮车
  • 我在good authority 上有它的发音是“twiddle”。在other hand 上,它可能读作“select”。
  • 为了爱你认为好的东西,你能用反对票阻止它吗?我已经明白了。

标签: python python-2.7


【解决方案1】:

~ 是一个一元运算符(即它只需要一个参数),它计算其参数的bitwise inverse。结果是-x - 1,因为在Two's complement 表示中,-x 相当于将所有位反转然后加一。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-20
    • 2013-11-03
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2020-03-19
    • 2020-08-26
    相关资源
    最近更新 更多