Python學習—字元串練習

Python字元串練習

  1. 輸入一行字元,統計其中有多少個單詞,每兩個單詞之間以空格隔開。如輸入: 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 = 0  s=input("輸入字元:")  for i in range(len(s)):      if i+1 > len(s);          count+=1      else:          if s[i] == ' ' and s[i+1] != ' ':              count+=1
  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] = 1 f = open("統計.txt","w") for i in dict: f.write(i+":"+str(dict[i])+"t") f.close() string = input("請輸入字元串:") function(string) 執行結果:

可以看到生成了「統計.txt」文件。打開查看是否正確寫入內容,

  1. (2017-好未來-筆試編程題)–練習
  • 題目描述: 輸入兩個字元串,從第一字元串中刪除第二個字元串中所有的字元。例如,輸入」They are students.」和」aeiou」,則刪除之後的第一個字元串變成」Thy r stdnts.」
  • 輸入描述: 每個測試輸入包含2個字元串
  • 輸出描述: 輸出刪除後的字元串
  • 示例1:
輸入      They are students.      aeiou  輸出      Thy r stdnts.

程式碼:

str1 = input("請輸入第一個字元串:")  str2 = input("請輸入第二個字元串:")  str3 = ''  for i in str2:      if i not in str3:          str3+=i  for i in str3:      str1=str1.replace(i,'')  print(str1)

運行結果:

  1. (2017-網易-筆試編程題)-字元串練習

小易喜歡的單詞具有以下特性: 1.單詞每個字母都是大寫字母 2.單詞沒有連續相等的字母 列可能不連續。 例如: 小易不喜歡"ABBA",因為這裡有兩個連續的'B' 小易喜歡"A","ABA"和"ABCBA"這些單詞 給你一個單詞,你要回答小易是否會喜歡這個單詞。

  • 輸入描述: 輸入為一個字元串,都由大寫字母組成,長度小於100
  • 輸出描述: 如果小易喜歡輸出"Likes",不喜歡輸出"Dislikes"

示例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")              break  else:      print("Likes")

執行結果: