您的位置:首页 > 编程语言 > Python开发

python:标识符必须以字母或下划线开头,后面跟字母,下划线或者数字

2017-03-21 18:42 99 查看
标识符合法性检查,首先要以字母或者下划线开始,后面要跟字母,下划线或者或数字.这个小例子只检查长度大于等于 2 的标识符
idcheck.py
#!/usr/bin/env python
'''
idcheck.py -- checks identifiers for validity
'''

import string        # string utility module

# create alphabet and number sets
alphas = string.ascii_letters + '_'
nums = string.digits

# salutation message and input prompt
print ('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 al
4000
phas + nums:
print ('invalid: remaining symbols must be alphanumeric')
break
else:
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python
相关文章推荐