码迷,mamicode.com
首页 > 其他好文 > 详细

idcheck 标识符合法性检查

时间:2015-12-02 14:26:44      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

#!/usr/bin/env python
#--*-- coding:utf-8 --*--
"""
标识符合法性检查,首先要以字母或者下划线开始,后面要跟字母,下划线或者数字
这个例子只检查长度大于等于2的标志符
"""

import string
alphas = string.letters + _
nums = string.digits

def menu():
    print Welcome to the Identifier Checker v1.0
    print Testees must be at least 2 chars long.
    #myInput = raw_input(‘Identifier to test?\n‘)


def runidchk(myInput):
    if len(myInput) > 1: #判读长度是否大于2
        if myInput[0] not in alphas: #首字母是否以字母或者下划线
            print "invalid:first symbol must be alphabetic"
        else: 
            for otherchar in myInput[1:]:
                if otherchar not in alphas + nums:
                    print "invalid:remaining symbols must be alphabetic"
                    break
                else:
                    print "okay as an Identifier"

if __name__ == __main__:
    while True:
        menu()
        runidchk(raw_input(Identifier to test?\n))

 

running result:

kevins-MacBook-Pro:chapter06 kevin$ python idcheck.py 
Welcome to the Identifier Checker v1.0
Testees must be at least 2 chars long.


Identifier to test?
__hello
okay as an Identifier
okay as an Identifier
okay as an Identifier
okay as an Identifier
okay as an Identifier
okay as an Identifier
Welcome to the Identifier Checker v1.0
Testees must be at least 2 chars long.


Identifier to test?
333
invalid:first symbol must be alphabetic

 

idcheck 标识符合法性检查

标签:

原文地址:http://www.cnblogs.com/magicpower/p/5012761.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!