简单字符串过滤练习

 1 # -*- coding:utf-8 -*-
 2 
 3 import string
 4 
 5 alphas = string.letters + '_'            #返回26个大小写字母
 6 nums = string.digits                    #返回字符串 0,1,2,3,4,5,6,7,8,9
 7 #print alphas
 8 #print nums
 9 print 'Welcome to the Identifier Checker v1.0'
10 print 'Testees must be at least 2 chars long.'
11 
12 myInput = raw_input('Identifier to test?')
13 
14 if len(myInput) > 1:                    #过滤长度小于2的字符串
15     if myInput[0] not in alphas:        #检查第一个字符串是不是字母或下划线,如果不是,输出结果并退出
16         print 'invalid: first symbol must bealphabetic'
17     else:
18         for otherChar in myInput[1:]:               #循环字符串 myInput 从索引位置1开始
19             if otherChar not in alphas + nums:      #检查字符串,如果包括非 alphas 中的字符, 打印输出
20                 print otherChar                     #输出非法字符
21                 print myInput.find(otherChar)       #输出第一个非法字符的索引
22                 print 'invalid: remainig symbols must be alphanumeric'
23                 break
24 else:
25     print 'okay as an identifier'
原文地址:https://www.cnblogs.com/Roger1227/p/3073649.html