標籤:字元列表
用python從字元列表中返回字串字元的位置
需要從字元列表中找出每個字元在字串中的位置,然後將整個字元位置返回到單個字串中,每個字元位置之間的空格除外最後一個。您需要忽略所有不在字元列表中的由az中的字元組成的字元。
策略:
首先,我們需要在列表中聲明az字元的列表。
alphabetlist = ["a", 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
接下來建立一個迴圈,它會遍曆字串中的每個字元,並在上面的字元列表中尋找每個字元的位置,如果字元不在列表中,則跳過迭代並轉到下一個字元。我們需要確保在搜尋開始之前字元已經被轉換為小寫字母,並且向包含零的返回索引(我們希望我們的索引從1開始而不是0開始)加1。
for ch in text: if(ch.lower() not in alphabetlist): continue else: ch = ch.lower() letterpos += str(alphabetlist.index(ch) + 1) + " "
最後返回字串位置,不要忘記截斷字串末尾的空格。完整的代碼如下:
def alphabet_position(text): if(len(text) == 0): # if the text is blank then return it return text alphabetlist = ["a", 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] letterpos = '' for ch in text: if(ch.lower() not in alphabetlist): continue else: ch = ch.lower() letterpos += str(alphabetlist.index(ch) + 1) + " " return letterpos.rstrip()
現在我們可以用string參數調用上面的函數來查看結果。
用python從字元列表中返回字串字元的位置