2

I have my own name saved as a string under the variable name. I want to find the character code for each character in my name and then add them all up using a for loop. This is what I've started with, no idea if it's staring about the right way

name = "Ashley Marie"
for index in name:
    ans = ord(index)
Ash
  • 35
  • 2
  • 9

2 Answers2

4

You can use map to apply the ord function on all of your characters and then use sum function to calculate the sum :

>>> name = "Ashley Marie"
>>> 
>>> sum(map(ord,name))
1140

You can also use a list comprehension to apply ord on your characters but when you are dealing with built-in function map has slightly more performance! So I suggest map.

Also for longest strings you can use a generator expression within sum,that doesn't create a list and can save a lots of memory:

sum(ord(i) for i in name)
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • Thank you. That does work but for what this is for I have to use a for loop, making things more difficult for me at the moment. – Ash Jun 25 '15 at 08:43
1

Kasra solution is the correct one, but you asked for a "for loop"...so here it is:

 name = "Ashley Marie"
    sum = 0
    for ch in map(ord, name):
        sum += ch
    print sum

or

name = "Ashley Marie"
sum = 0
 for c in name:
    sum += ord(c)
print sum
Nerkyator
  • 3,976
  • 1
  • 25
  • 31