Chapter 6.序列:字符串,列表和元组
这章内容比较多啊,看得比较久,而且题目又难很多。
6.1鉴定一个字符串是否是另外一个字符串的字串,这道题目不是很确定,好像没有直接的判定吧。
直接是否内建的序列函数 in ?
1 >>> a = 'or' 2 >>> b = 'favorite' 3 >>> a in b 4 True
strin模块也有类似的函数,不知道算不算
1 >>> b.count(a) 2 1 3 >>> b.find(a) 4 3 5 >>> b.index(a) 6 3 7 >>> b.rindex(a) 8 3 9 >>> b.rindex(a) 10 3
6-2。修改idcheck.py脚本,使之可以检测长度为一的标识符,并且可以识别Python关键字(通过keyword模块的keyword.kwlist)来辅助。
其实不太难,跟着感觉走就对了。
1 #!/usr/bin/env python 2 #-*-coding=utf-8-*- 3 4 import string 5 import keyword 6 7 alphas = string.letters + '_' 8 nums = string.digits 9 keywords = keyword.kwlist 10 11 flag = True 12 13 print 'Welcome to the Identifier Checker v2.0' 14 myInput = raw_input('Identifier to test?') 15 16 if len(myInput) >= 0: 17 if myInput in keywords: 18 flag = False 19 print '''invalid:the identifier must not be keyword.''' 20 elif myInput[0] not in alphas: 21 flag = False 22 print '''invalid:first symbol must be alphabetic''' 23 else: 24 for otherChar in myInput[1:]: 25 if otherChar not in alphas+nums: 26 flag = False 27 print '''invalid:remaining symbols must be alphanumeric''' 28 break 29 30 if flag == True: 31 print '''okay as an identifier''' 32 33