Python習題集(十七)


 

每天一習題,提升Python不是問題!!有更簡潔的寫法請評論告知我!

https://www.cnblogs.com/poloyy/category/1676599.html

 

題目

寫一個函數alphabet_index,該函數參數是1個字符串,

要求該函數返回一個新字符串,里面是 參數字符串中每個字母依次對應的 數字。如果是非字母,則忽略它

字母"a""A" 都對應 1, "b""B"都對應2, "c""C"對應3, 依次類推

比如

alphabet_index("Wow, does that work?")
➞ "23 15 23 4 15 5 19 20 8 1 20 23 15 18 11"

alphabet_index("The river stole the gods.")
➞ "20 8 5 18 9 22 5 18 19 20 15 12 5 20 8 5 7 15 4 19"

alphabet_index("We have a lot of rain in June.")
➞ "23 5 8 1 22 5 1 12 15 20 15 6 18 1 9 14 9 14 10 21 14 5"

 

解題思路

  1. 將字符串統一為大寫字母
  2. 需要設置一個對比值
  3. 大寫A的ASCII碼為65,但A對應1,所以設置一個對比值為64
  4. 循環字符串,如果是字母則換算出它的ASCII碼,再減去對比值

 

答案

def alphabet_index(strs):
    strs = strs.upper()
    temp = 64
    res = ""
    for i in strs:
        if i.isalpha():
            res += str(ord(i) - temp) + " "
    print(res)


alphabet_index("Wow, does that work?")
alphabet_index("The river stole the gods.")
alphabet_index("We have a lot of rain in June.")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM