標籤:代碼 proc else 大寫 water dict 方法 split col
Python字串練習
- 輸入一行字元,統計其中有多少個單詞,每兩個單詞之間以空格隔開。如輸入: This is a c++ program. 輸出:There are 5 words in the line. 【考核知識點:字串操作】
代碼:s=input("請輸入一行句子:")list = s.split(‘ ‘)print("There are %d words in the line." %len(list))
運行結果:
另外考慮到有時候手抖多敲了空格,於是又想了一種方法:
count = 0s=input("輸入字元:")for i in range(len(s)): if i+1 > len(s); count+=1 else: if s[i] == ‘ ‘ and s[i+1] != ‘ ‘: count+=1
- 給出一個字串,在程式中賦初值為一個句子,例如"he threw three free throws",自編函數完成下面的功能:
1)求出字元列表中字元的個數(對於例句,輸出為26);
2)計算句子中各字元出現的頻數(通過字典儲存); ---學完字典再實現
3) 將統計的資訊儲存到檔案《統計.txt》中; --- 學完檔案操作再實現
代碼:def function(s):print("字串中字元的個數為: %d" %len(s))dict = {}for i in s: if i in dict: dict[i] += 1 else: dict[i] = 1f = open("統計.txt","w")for i in dict: f.write(i+":"+str(dict[i])+"\t")f.close()string = input("請輸入字串:")function(string)
執行結果:
可以看到產生了“統計.txt”檔案。開啟查看是否正確寫入內容,
- (2017-好未來-筆試編程題)--練習
輸入 They are students. aeiou輸出 Thy r stdnts.
代碼:
str1 = input("請輸入第一個字串:")str2 = input("請輸入第二個字串:")str3 = ‘‘for i in str2: if i not in str3: str3+=ifor i in str3: str1=str1.replace(i,‘‘)print(str1)
運行結果:
- (2017-網易-筆試編程題)-字串練習
小易喜歡的單詞具有以下特性:
1.單詞每個字母都是大寫字母
2.單詞沒有連續相等的字母
列可能不連續。
例如:
小易不喜歡"ABBA",因為這裡有兩個連續的‘B‘
小易喜歡"A","ABA"和"ABCBA"這些單詞
給你一個單詞,你要回答小易是否會喜歡這個單詞。
樣本1 :
輸入 AAA輸出 Dislikes
代碼:
s = input("請輸入字串:")for i in range(len(s)): if s[i] < ‘A‘ or s[i] >‘Z‘: print("Dislike") break else: if i < len(s)-1 and s[i] == s[i+1]: print("Dislike") breakelse: print("Likes")
執行結果:
Python學習—字串練習