6–2. 字符串标识符.修改例6-1 的idcheck.py 脚本,使之可以检测长度为一的标识符,并且可以识别Python 关键字,对后一个要求,你可以使用keyword 模块(特别是keyword.kelist)来帮你.
import string from keyword import iskeyword nums = string.digits characters = 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 !" % value return others = val[1:] for ch in others: if ch not in (nums+characters): print "error character :%s" % ch return print 'valid id!' if __name__=="__main__": while True: value = raw_input(">>>\n") value = value.strip() if value == "quit": break check(value)