chillbro chillbro - 29 days ago 7
Python Question

Consecutive addition of numbers in a string

I'm a new programmer learning python and am having trouble with how to approach this task:

So essentially I have a string of numbers to read imported from a file, and need to add the sum of the first number to the second and convert it to the correct ascii character. So, for example if I am reading the string:

'36 30 25 40 80 4'


I would want to add 36 to 30, then 25 to 40, then 80 to 4 and so on, before converting them to the corresponding ASCII character and printing (so in this case 'CAT').

So far i recognize that i need to use a split command to split the string, and then a for loop to take the data for consecutive numbers. I can get the correct value for the first letter, but am having trouble 'telling' the program to atuomatically move on to add [2] to [3] after adding [1] to [0]. I also need to do this for multiple lines.

Again, I'm a new coder so any help is greatly appreciated. Thanks!

Answer

Another method that is less opaque (though more verbose) than Patrick's proposal would be:

>>> x = '36 30 25 40 80 4'
>>> nums = [int(n) for n in x.split()]
>>> ''.join(chr(sum(nums[i:i+2])) for i in range(0, len(nums), 2))
'BAT'