I am wondering how to check a string for certain letters to attach values to them so I can add them up, then return the total to the user.
How would I go with doing so?
I am wondering how to check a string for certain letters to attach values to them so I can add them up, then return the total to the user.
How would I go with doing so?
a_string = "abcde"
letters = ["a", "e", "i", "o", "u"]
for x in a_string:
if(x in letters):
print(x+" is in "+a_string)
From here you can use a dictionary to map "x" to a point value.
This can easily be done using a dictionary and for loop.
# Dictionary matching letters to values
letter_val = {'a': 1,
'b': 2,
'c': 3,
'd': 4
}
def myFunction(s):
"""Function takes a string and checks each character
against the dictionary values. If letter is in then
add value to result"""
res = 0
for char in s:
if char in letter_val:
res += letter_val[char]
return res
If you do not want to assign specific values to the letters, you can use the Unicode integers and deduct the Unicode start value to get 1 through 24 (a-z):
>>> a = 'aBcDefghijklmnopqrstuvwXyZ'
>>> tot=0
>>> for i in a:
... tot+=int(ord(i.lower()))-96
...
>>> tot
351
ord()
returns the Unicode value of the character, where "a" = 97 and i.lower()
converts all the letters to lower-case.
To run using upper-case letters use i.upper()
instead and deduct 64, where Unicode value of "A" is 65