I'm trying to make a function in python that would take a word, find ASCII value of each character in a word, then multiply each of the value by the position of the character in that word and sum together. I came up with below however I don't know how to multiply each 'x' with the position number of each char.
mystring = 'AZC'
total = 0
for c in mystring:
x = ord(c)
total += x
print(total)
this code returns value 222 (65 for 'A' + 90 for 'Z' + 67 for 'C') but I need 65 * 1 + 90 * 2 + 66 * 3 = 443 It will probably have something to do with substring but I am lost
Use enumerate()
to get the positions. And you can use the sum()
function to add them all together.
total = sum(pos * ord(c) for pos, c in enumerate(mystring, 1))
The second argument 1
makes it start the positions at 1
instead of 0
.