Python实例浅谈之一标识符检查

一、问题

      Python标识符必须以字母或下划线开头,后面跟字母、下划线或者数字,且标识符不能为关键字,如何有效的检查?

二、解决

1、方法一

(1)python脚本
新建idcheck.py,输入代码,然后执行pythonidcheck.py。

#!/usr/bin/env python
'''
$Id$

idcheck.py -- checks identifiers for validity

This application is limited in that it currently only supports
checking identifiers with length > 1 (does not process identifiers
of length greater than 1.  This application also does not recognize
do keywords.

Exercise:

    6-2) update this script to process identifiers of length 1
        as well as recognizing keywords as invalid identifiers
        (for use by the programmer; they are valid Python
        identifiers otherwise).
'''

import string        # string utility module

# create alphabet and number sets
alphas = string.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 = raw_input('Identifier to test >>> ')

# only take action for identifiers with length >= 1
if len(inp) >= 1:

    # first character must be alphabetic
    if inp[0] not in alphas:
        print 'invalid: first symbol must be alphabetic'

    # remaning characters can be alphanumeric
    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'
(2)运行结果

        其中for-else结构中else语句是一个可选项,它只在 for 循环完整的结束而没有遇到break 时执行。
        性能:for otherChar in inp[1:]:循环中的 if 语句执行了合并两个字符串的操作,被合并的这两个字符串从始至终就没变过,而每次都会重新进行一次计算,需要创建新对象,如果先把这两个字符串存为一个新字符串,就可以直接引用这个字符串而不用进行重复计算了。所以可以改为:

        alphnums = alphas + nums
        for otherChar in inp[1:]:
            if otherChar not in alphnums:
                print 'invalid: remaining symbols must be alphanumeric'
                break
        else:
            print "okay as an identifie

2、方法二

       针对方法一中不能检查标识符是否为Python的关键字的问题(关键字是不允许用做标识符的),故引入keyword模块中的kwlist关键字列表。
(1)python脚本
新建idcheck2.py,输入代码,然后执行python idcheck2.py。

#!/usr/bin/env python

from keyword import kwlist
import string

ALPHAS = string.ascii_letters + '_'
NUMS = string.digits

def main():
    print 'Welcome to the Identifier Checker v2.0'
    myInput = raw_input('Identifier to test >>>').strip()

    if len(myInput) == 0:
	print "ERROR: no identifier candidate entered"
	return

    if myInput in kwlist:
	print "ERROR: %r is a keyword" % myInput
	return

    alnums = ALPHAS + NUMS
    for i, c in enumerate(myInput):
	if i == 0 and c not in ALPHAS:
	    print 'ERROR: first symbol must be alphabetic'
	    break
	if c not in alnums:
	    print 'ERROR: remaining symbols must be alphanumeric'
	    break
    else:
	print "okay as an identifier"

if __name__ == '__main__':
    main()

其中Python的关键字列表为:


(2)运行结果

三、总结

(1)Python代码性能的分析和提高还需要不停的总结,在循环中尽量不要重复计算值不变的字符串。
(2)若有更好的设计或思路,请留言,在此先感谢!
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乌托邦2号

博文不易,支持的请给予小小打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值