1. 字符串, string模块中是否有一种字符串方法或者函数可以帮我鉴定一下一个字符串是否是另一个大字符串的一部分?
1 str1 = 'abcdefghijklmnopqrstuv' 2 print str1.find('abcd') #若找到则返回子串的起始index, 若未找到则返回-1 3 print str1.count('abd') #若count数量大于0 则表示子串是str1的一部分. 4 print str1.index('abc') #若未找到返回异常, 找到则返回相应的index.
2. 字符串标示符, 修改6-1的idcheck.py脚本,使之可以检测长度为一的标示符,并且可以识别python关键字, 对后一个要求,你可以用keyword模块(特别是keyword.kwlist)来辅助
1 import string 2 import keyword 3 4 alphas = string.letters + '_' 5 nums = string.digits 6 kw = keyword.kwlist 7 8 print 'Welcome to the Identifier Checker v1.0' 9 print "Testees must be at least 2 chars long." 10 myInput = raw_input('Indetifier to test --> ') 11 12 if len(myInput) == 1: 13 if myInput[0] not in alphas: 14 print "invalid: first symbol must be alphabetic" 15 else: 16 print "Ok as an identifier length 1" 17 18 elif len(myInput) > 1: 19 if myInput[0] not in alphas: 20 print "invalid: first symbol must be alphabetic" 21 elif myInput in kw: 22 print "Invalid: it a python keyword" 23 else: 24 for otherchar in myInput[1:]: 25 if otherchar not in alphas + nums: 26 print "invalid: remaining symbols must be alphanumeric" 27 break 28 else: 29 print "Okay as an identifier"
3. 排序
(a) 输入一串数字,并从大到小排列之.
(b)跟a一样,不过要用字典顺序从大到小排列
1 #coding:utf-8 2 str1 = raw_input("Enter some numbers -->").split() 3 ltnum = [] 4 for ch in str1: 5 ltnum.append(int(ch)) 6 lt2 = sorted(ltnum)[::-1] 7 8 9 ltDict = [] 10 for ch in str1: 11 ltDict.append(ch) 12 ltDict2 = sorted(ltDict)[::-1] 13 print lt2 14 print ltDict2
4. 算术. 更新上一章里面你的得分测试练习方案, 把测试得分放到一个列表中去, 你的代码应该可以计算出一个平均分.见联系2-9 和5-3
1 def scoreCalculate(score): 2 if score < 60: 3 rank = 'F' 4 elif score < 70: 5 rank = 'D' 6 elif score < 80: 7 rank = 'C' 8 elif score < 90: 9 rank = 'B' 10 else: 11 rank = 'A' 12 return rank 13 14 yourscore = [] 15 while True: 16 score = raw_input("Enter your score (q for quit)-->") 17 if score == 'q': 18 break 19 else: 20 yourscore.append(int(score)) 21 average = float(sum(yourscore)) / len(yourscore) 22 print average
5. 字符串
(a)更新你在练习2-7里面的方案, 使之可以每次向前向后都显示一个字符串的一个字符.
(b)通过扫描来判断两个字符串是否匹配(不能使用比较操作符cmp()內建函数). 附加题: 在你的方案中加入大小写区分.
(c)判断一个字符串是否重现(后面跟前面一致), 附加题: 在处理了严格的回文之外,加入对例如控制符号和空格的支持.
(d) 接受一个字符在其后面加一个反向拷贝,构成一个回文字符串.
(a) # 理解为了正序和逆序.
1 #coding:utf-8 2 str1 = raw_input("Enter a string -->") 3 4 for ch in str1: 5 print ch, 6 7 print 8 print "reversed" 9 for ch in str1[::-1]: 10 print ch,
(b)
#coding:utf-8 str1 = raw_input("Enter the first string -->") str2 = raw_input("Enter the second string -->") if len(str1) != len(str2): print "They are not match.they have different length" else: for i in xrange(len(str1)): if str1[i] != str2[i]: print "They are not matchs." break else: print "They are matchs."
(c)
1 #coding:utf-8 2 str1 = raw_input("Enter a string -->") 3 4 if len(str1) % 2 != 0: 5 print "The string is not huiwen." 6 else: 7 partitionNum = len(str1) // 2 8 subStr1 = str1[:partitionNum] 9 subStr2 = str1[partitionNum:][::-1] 10 for i in xrange(len(subStr1)): 11 if subStr1[i] != subStr2[i]: 12 print "The string is not huiwen" 13 break 14 else: 15 print "The string is huiwen"
(d)
1 #coding:utf-8 2 str1 = raw_input("Enter a string -->") 3 4 subStr = str1[::-1] 5 str1 +=subStr 6 print str1
6. 字符串, 创建一个string.strip()的替代函数: 接受一个字符串,去掉它前面和后面的空格(如果使用string.*strip()函数那本练习就没有意义了)
1 #coding:utf-8 2 str1 = raw_input("Enter a string -->") 3 print len(str1) 4 if str1[0] == ' ': 5 if str1[-1] == ' ': 6 str1 = str1[1:-1] 7 else: 8 str1 = str1[1:] 9 elif str1[-1] == ' ': 10 str1 = str1[:-1] 11 12 print str1,len(str1)
7. 调试, 看一下在例6.5 中给出的代码(buggy.py)
(a) 研究这段代码, 并描述这段代码想做什么,在所有的(#)处都要填写你的注释.
(b)这个程序有一个很大的问题, 比如输入6,12,20,30 等它会死掉,实际上它不能处理任何的偶数,找出原因.
(c) 修正(b)中提出的问题.
1 #coding:utf-8 2 #得到一个用户输入 3 num_str = raw_input('Enter a number: ') 4 5 #将用户输入的数字字符转化成int类型 6 num_num = int(num_str) 7 8 #创建一个1~用户输入数字的列表 9 fac_list = range(1, num_num + 1) 10 print "Before:",fac_list 11 12 # 定义一个整型变量并赋值为0 13 i = 0 14 deleted = [] 15 16 # while循环判断条件 17 while i < len(fac_list): 18 # 用户输入数字对里表中index 为i的数字求余. 19 if num_num % fac_list[i] == 0: 20 deleted.append(fac_list[i]) #修改此处. 21 22 # 变量自增. 23 i = i + 1 24 for ch in deleted: 25 fac_list.remove(ch) 26 27 print "After:", fac_list
8. 列表, 给出一个整型值,返回代表该值的英文, 比如输入89返回"eight-nine". 附件题: 能够返回符合英文语法规则的形式, 比如输入"89" 返回"eighty-nine". 本练习中的值限定在0~1000.
1 #coding=utf-8 2 units = ['zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','forteen','fifteen','sixteen','seventeen','eighteen','nineteen'] 3 tens = ['twenty','thirty','forty','fifth','sixty','seventy','eighty','ninety'] 4 hundreds = ['hundreds'] 5 6 myInput = raw_input("Enter an integer -->") 7 myInput_num = int(myInput) 8 9 if myInput_num <=19: 10 print units[myInput_num] 11 elif myInput_num <100: 12 tens_unit = int(myInput[0])-2 13 unit_unit = int(myInput[1]) 14 if unit_unit == 0: 15 print tens[tens_unit] 16 else: 17 print tens[tens_unit] + '-' + units[unit_unit] 18 elif myInput_num < 1000: 19 if myInput_num <= 119: 20 hundred_unit = int(myInput[0]) 21 unit_unit = int(myInput[1:]) 22 print units[hundred_unit] + ' hundreds and ' + units[unit_unit] 23 else: 24 hundred_unit = int(myInput[0]) 25 tens_unit = int(myInput[1])-2 26 unit_unit = int(myInput[2]) 27 if unit_unit == 0: 28 print units[hundred_unit] + ' hundreds and ' + tens[tens_unit] 29 else: 30 print units[hundred_unit] + ' hundreds and ' + tens[tens_unit] + '-' + units[unit_unit]
9. 转换, 为练习5-13 写一个姊妹函数,接受分钟数,返回小时数和分钟数.总时间不变,并且要求小时数尽可能大.
1 #coding=utf-8 2 inputMinutes = raw_input("Enter a minutes numer to transfer -->") 3 inputMinutes = unicode(inputMinutes) 4 if not inputMinutes.isnumeric(): 5 print "WTF" 6 else: 7 inputMinutes = int(inputMinutes) 8 Hours,Minutes = divmod(inputMinutes,60) 9 print "There are %d hours and %d Minutes" %(Hours,Minutes)
10. 字符串, 写一个函数,返回一个跟输入字符串相似的字符串,要求字符串的大小写反转.比如,输入"Mr.Ed", 应该返回"mR.eD"作为输出.
1 #coding=utf-8 2 def caseSwap(str1): 3 return str1.swapcase() 4 5 myInput = raw_input("Enter a string to swap -->") 6 print caseSwap(myInput)
#使用了swapcase()内建函数. 也可以使用isupper() 和islower() 来逐个字符转换.
11. 转换.
(a) 创建一个从整形到IP地址的转换程序, 如下格式: WWW.XXX.YYY.ZZZ
(b) 更新你的程序, 使之可以逆转换.
1 #coding=utf-8 2 3 def ipTransfer(ipaddress): 4 """将接受到的输入转换成www.xxx.yyy.zzz的格式. 5 6 """ 7 transferedIP = [] 8 ipLength = len(ipaddress) 9 if ipLength != 12: 10 print "the ip address is invalid." 11 else: 12 for i in xrange(ipLength // 3): 13 transfer,ipaddress = ipaddress[:3],ipaddress[3:] 14 transferedIP.append(transfer) 15 return '.'.join(transferedIP) 16 17 #将上面得到的IP地址逆转, 即删除IP地址中的"." 18 def ipTransfer2(ipaddress):
19 if len(ipaddress) != 15: 20 print "the ip address is invalid." 21 else: 22 ipaddress = list(ipaddress) 23 for ch in ipaddress: 24 if ch == '.': 25 ipaddress.remove(ch) 26 return ''.join(ipaddress) 27 28 yourIP = raw_input("Enter your IP -->") 29 transferedIpAddress = ipTransfer(yourIP) 30 print "the TransferedIpAddress is %s" %transferedIpAddress 31 transferedBackIP = ipTransfer2(transferedIpAddress) 32 print "the transferedBackIp is %s" %transferedBackIP
12. 字符串.
(a)创建一个名为findchr()的函数,函数声明如下.
def findchr(string,char)
findchr()要在字符串string中查找字符char,找到就返回该值的索引,否则返回-1.不能用string.*find()或者string.*index函数和方法
(b) 创建另一个叫rfindchr()的函数,查找字符char最后一次出现的位置.它跟findchr()工作类似,不过它是从字符串的最后开始向前查找的.
(c) 创建第三个函数,名字叫subchr(),声明如下.
def subchr(string,origchar,newchar)
subchr()跟findchr()类似,不同的是如果找到匹配的字符就用新的字符替换原先的字符.返回修改后的字符串.
1 #coding=utf-8 2 #(a) 3 def findchr(originalString,char): 4 stringLength = len(originalString) 5 for i in xrange(stringLength): 6 if originalString[i] == char: 7 return i 8 else: 9 return -1 10 11 #(b) 12 def rfindchr(originalString,char): 13 stringLength = len(originalString) 14 for i in range(stringLength-1,-1,-1): 15 if originalString[i] == char: 16 return i 17 else: 18 return -1 19 #(c) 20 def subchr(originalString,origchar,newchar): 21 listString = list(originalString) 22 listLength = len(listString) 23 for i in xrange(listLength): 24 if listString[i] == origchar: 25 listString[i] = newchar 26 27 return ''.join(listString) 28 29 30 yourString = raw_input("Enter the original string.-->") 31 yourchar = raw_input("Enter the char you wanna find -->") 32 yourreplacechar = raw_input("Enter the char you wanna to replace to -->") 33 34 #print findchr(yourString,yourchar) 35 #print rfindchr(yourString,yourchar) 36 print subchr(yourString,yourchar,yourreplacechar)
13. 字符串, 实现一个atoc(),接受单个字符串做参数输入,一个表示复数的字符串,例如'-1.23e+4-5.67j'返回相应的复数对象,你不能用eval函数,但可以使用complex()函数,而且你智能在如下的限制下使用: complex():complex(real,image)的real 和imag都必须是浮点值