我是靠谱客的博主 迷路烧鹅,这篇文章主要介绍Python检查标识符是否合法,现在分享给大家,希望可以做个参考。

所谓的合法标识符是:以字母,下划线开头;全部则是由字母,数字,下划线组成。

程序不难,注释如下:

import string

#注:python2中的string成员letters在python3中改为了ascii_letters
alphas=string.ascii_letters+'_'
nums=string.digits

print('合法标识符检查。。。')
print('测试字符串长度至少为2')
while True:
    myInput=input('键入字符串')
    if len(myInput) > 1:
        if myInput[0] not in alphas:
            print('##标识符首位非法##')
        elif True:
            allChar = alphas + nums
            for otherChar in myInput[1:]:
                if otherChar not in allChar:
                    print('##剩余字符串中存在非法标识符##')
                    break
                else:
                    break
        print('检查结束')

if __name__=='__main__':
    test()

最后

以上就是迷路烧鹅最近收集整理的关于Python检查标识符是否合法的全部内容,更多相关Python检查标识符是否合法内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(134)

评论列表共有 0 条评论

立即
投稿
返回
顶部