0

我写了一些代码,它为我提供了带有英文字母位置的单词的总和,但我正在寻找可以打印这样一行的东西:

书:2 + 15 + 15 + 11 = 43

def convert(string):
    sum = 0

    for c in string:
        code_point = ord(c)
        location = code_point - 65 if code_point >= 65 and code_point <= 90 else code_point - 97
        sum += location + 1

    return sum

print(convert('book'))
4

1 回答 1

0
def convert(string):
    parts = []
    sum = 0
    for c in string:
        code_point = ord(c)
        location = code_point - 65 if code_point >= 65 and code_point <= 90 else code_point - 97
        sum += location + 1
        parts.append(str(location + 1))
    return "{0}: {1} = {2}".format(string, " + ".join(parts), sum)

print(convert('book'))

这是输出:

书:2 + 15 + 15 + 11 = 43

string.format有关和的更多信息string.join

于 2018-03-04T21:28:33.217 回答