题目

Replace With Alphabet Position

替换为字母表位置

描述

Welcome.
In this kata you are required to, given a string, replace every letter with its position in the alphabet.

If anything in the text isn't a letter, ignore it and don't return it.

欢迎

在这个kata中,你需要给定一个字符串,用它在字母表中的位置替换每个字母。

如果文本中有任何内容不是字母,请忽略它,不要返回。

例子

alphabet_position("The sunset sets at twelve o' clock.")

Should return "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" (as a string)

思路

这题思路很简单,就是做字母的减法,但是这里有个注意点就是,a = 1,也就是说从1开始,因为我们做减法的基准是a,所以结果加1.

只有字母才做减法,其他的忽略

对于python来说,不能直接做字母的减法,需要使用ord转换成对应的ASCII数值

##完整代码

def alphabet_position(text):
    # 保存结果
    result = []
    # 遍历这个字符串
    for i in text:
        # 判断是否是字母
        if i.isalpha():
            # 这里将字母变成小写字母,因为首字母是大写,如果和a减的话,为负数,并且题意也是转换为小写字母
            i = i.lower()
            # 这里是个注意点,从1开始算
            result.append(str(ord(i) - ord("a") + 1))
    # 组合起来
    return " ".join(result)
    pass