Python program to find sum of ASCII values of each word in a sentence
Hi! in this tutorial we are going to learn how to write Python code that finds the sum of ASCII values of each word in a sentence. Let’s start with the code first-
s=input() x=[] l=[] l=s.split(' ') for w in l: count=sum(map(ord,w)) x.append(count) print('sum of each ASCII values of a word in the given string is:') for i in range(len(l)): print(l[i],'->',x[i],end=',') print() print('total sum of ASCII values of all words in the given string is:') print(sum(x))
If you don’t want to take user input you can simply use variable s
to store the word as a string just like this:
s="This is my Name" x=[] l=[] l=s.split(' ') for w in l: count=sum(map(ord,w)) x.append(count) print('sum of each ASCII values of a word in the given string is:') for i in range(len(l)): print(l[i],'->',x[i],end=',') print() print('total sum of ASCII values of all words in the given string is:') print(sum(x))
Sum of ASCII values of each word in a sentence
First, we take input from the user using input()
function. We store the input string to a variable named s
. Then, we declare an empty list named x
which is used to the sum of ASCII values of each individual word in the string entered by the user.
Then, we split the given string into separate individual words using the split()
function and store the result in an empty list named as l. And, to neglect the spaces between words we passed an empty string on which the splitting action takes place. Now, we traverse the whole list l and using map()
function we apply ord()
function to each character in every word to get their ASCII value and add them using sum()
. After every iteration, we append the sum of ASCII value of each word separately in list x.
Now, we print the sum of ASCII values of an individual word using the values stored in list x.
And at last, we print the total sum of ASCII values of all the words in the string entered by the user.
Output-
My name is satyam sum of each ASCII values of a word in the given string is: My -> 198,name -> 417,is -> 220,satyam -> 655, total sum of ASCII values of all words in the given string is: 1490
Leave a Reply