python核心编程 第六章练习6-2

来源:互联网 发布:淘宝联盟领内部优惠券 编辑:程序博客网 时间:2024/05/21 20:21

6–2. 字符串标识符.修改例6-1 的idcheck.py 脚本,使之可以检测长度为一的标识符,并且可以识别Python 关键字,对后一个要求,你可以使用keyword 模块(特别是keyword.kelist)来帮你.

import stringfrom keyword import iskeywordnums = string.digitscharacters = string.letters + '_'def check(val):length = len(val)if length == 0:print "empty id!"return if val[0] not in characters:print "error! The first character must me '_' or letters "return if iskeyword(value):print "error ! %s is a key word !" % valuereturn others = val[1:]for ch in others:if ch not in (nums+characters):print "error character :%s" % chreturn print 'valid id!'if __name__=="__main__":while True:value = raw_input(">>>\n")value = value.strip()if value == "quit":breakcheck(value)