-2

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?

genieSessions
  • 29
  • 1
  • 1
  • 9
  • 2
    Possible duplicate of [Does Python have a string contains substring method?](http://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method) – AutomatedOrder Oct 16 '15 at 16:03
  • Have a look at this: http://stackoverflow.com/questions/5188792/how-to-check-a-string-for-specific-characters This will help you. – Leon Oct 16 '15 at 16:11

3 Answers3

2
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.

0

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
Steven Summers
  • 5,079
  • 2
  • 20
  • 31
0

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

Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60