Python學習—字串練習

來源:互聯網
上載者:User

標籤:代碼   proc   else   大寫   water   dict   方法   split   col   

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 = 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
  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”檔案。開啟查看是否正確寫入內容,

  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+=ifor 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")            breakelse:    print("Likes")

執行結果:

Python學習—字串練習

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.