Python编程:查看python语法中的关键字keyword
  TEZNKK3IfmPf 2023年11月15日 77 0

python2

$ workon py2

(py2)$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> import keyword

>>> dir(keyword)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__',
 'iskeyword', 'kwlist', 'main']

>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 
'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 
'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 
'with', 'yield']

>>> len(keyword.kwlist)
31

>>> keyword.iskeyword("yield")
True

python3

$ workon py3

(py3)$ python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 03:03:55)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> import keyword

>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 
'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 
'return', 'try', 'while', 'with', 'yield']

>>> len(keyword.kwlist)
33

so:


  1. python2中的关键字:31个

  2. python3中的关键字:33个


比对关键字差异

py2 = ['and', 'as', 'assert', 'break', 'class', 'continue', 'def',
'del', 'elif', 'else', 'except', 'exec', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not',
'or', 'pass', 'print', 'raise', 'return', 'try', 'while',
'with', 'yield']

py3 = ['False', 'None', 'True', 'and', 'as', 'assert', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']

print(set(py2) - set(py3))
# {'print', 'exec'}

print(set(py3) - set(py2))
# {'True', 'False', 'None', 'nonlocal'}

so:


  1. python2中的 {'print', 'exec'} 关键字在python3中已经去除

  2. python3中添加了关键字 {'True', 'False', 'None', 'nonlocal'}

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   34   0   0 python开发语言
  TEZNKK3IfmPf   2024年05月31日   27   0   0 python
  TEZNKK3IfmPf   2024年05月31日   27   0   0 python
TEZNKK3IfmPf