有这样一道题目: 字符串标识符.修改例 6-1 的 idcheck.py 脚本,使之可以检测长度为一的标识符,并且可以识别 Python 关键字,对后一个要求,你可以使用 keyword 模块(特别是 keyword.kelist)来帮你.
我最初的代码是:
复制代码 代码如下:
import string
import keyword
import sys
keyWords = keyword.kwlist
charForId = string.letters + "_"
numForId = string.digits
idInput = raw_input("Input your words,please!")
if idInput in keyWords:
print "%s is keyword fot Python!" % idInput
else:
lenNum = len(idInput)
if(1 == lenNum):
if(idInput in charForId and idInput != "_"):
print "%s is legal identifier for Python!" % idInput
else:
print "%s isn't legal identifier for Python!" % idInput
else:
if(idInput[0:1] in charForId):
legalstring = charForId + numForId
for item in idInput[1:]:
if (item not in legalstring):
print "%s isn't legal identifier for Python!" % idInput
sys.exit(0)
print "%s is legal identifier for Python!2" % idInput
else:
print "%s isn't legal identifier for Python!3" % idInput
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8