python - ~ 运算符在 Python 中有什么作用

标签 python python-2.7

<分区>

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

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

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

最佳答案

~是计算 bitwise inverse 的一元运算符(即它只接受一个参数)它的论点。结果是 -x - 1,因为在 Two's complement 中表示,-x 等同于反转所有位然后加一。

关于python - ~ 运算符在 Python 中有什么作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18742078/

相关文章:

python - 如何使用 MYSQL/Python/Django 对表中包含相似元素的行进行分组?

python - 如何使 absolute_import 成为所有模块的默认值

python-2.7 - Python - 将 TCP 套接字对象传递给多处理队列

python - 带有gevent的mongoengine,如何关闭/结束连接?

python - 构建 gem5.opt 时,我得到 'ImportError: no module named six'

python - OpenCV Python:distCoeffs2不是数字元组

python - 使 pypy 可用于 Windows 上的 pyscripter(或任何其他 ide)?

Python神秘地执行其他幻影脚本

python - python中的嵌套条件

python - jsonpickle 忽略集合双端队列的 maxlen