标识符合法性检查,首先要以字母或者下划线开始,后面要跟字母,下划线或者或数字.这个小例子只检查长度大于等于 2 的标识符
idcheck.py
#!/usr/bin/env python'''idcheck.py -- checks identifiers for validity'''import string # string utility module# create alphabet and number setsalphas = string.ascii_letters + '_'nums = string.digits# salutation message and input promptprint ('Welcome to the Identifier Checker v1.0')print ('Testees must be at least 2 chars long.')inp = input('Identifier to test ?')if len(inp) >= 1:if inp[0] not in alphas:print ('invalid: first symbol must be alphabetic')else:for otherChar in inp[1:]:if otherChar not in alphas + nums:print ('invalid: remaining symbols must be alphanumeric')breakelse:print ("okay as an identifier")else:print ('invalid: length must be >= 1')
运行结果 1:
Welcome to the Identifier Checker v1.0
Testees must be at least 2 chars long.
Identifier to test -> 123_das
invalid: first symbol must be alphabetic
————————————————————
运行结果 2:
Welcome to the Identifier Checker v1.0
Testees must be at least 2 chars long.
Identifier to test -> _123sdad
okay as an identifier