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

标识符合法性检查,首先要以字母或者下划线开始,后面要跟字母,下划线或者或数字.这个小例子只检查长度大于等于 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 alphas + 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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值