用python從字元列表中返回字串字元的位置

來源:互聯網
上載者:User

標籤:字元列表

用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從字元列表中返回字串字元的位置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.