天天看點

Python程式設計:檢視python文法中的關鍵字keyword

python 2

$ 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'}      
  1. python2中的 {'print', 'exec'}關鍵字在python3中已經去除
  2. python3中添加了關鍵字 {'True', 'False', 'None', 'nonlocal'}