用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参数调用上面的函数来查看结果。