How can I find the alphabetic position of the letters in a word and then add the numbers up?

51 Views Asked by At

I wrote some of the code which gives me the total of the word with the position of the English alphabet but I am looking for something that prints the line like this:

book: 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'))
1

There are 1 best solutions below

0
On
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'))

Heres the output:

book: 2 + 15 + 15 + 11 = 43

More info on string.format and string.join.