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都必須是浮點值
