简体   繁体   中英

How do I assign a numerical value to each uppercase Letter?

How do i assign a numerical value to each uppercase letter, and then use it later via string and then add up the values.

EG.

A = 1, B = 2, C = 3 (etc..)

string = 'ABC'

Then return the answer 6 (in this case).

base = ord('A') - 1
mystring = 'ABC'
print sum(ord(char) - base for char in mystring)

You can use ord to get the ascii code, then subtract 64.

def codevalue(char):
    return ord(char) - 64
import string

letter_to_numeral = dict(zip(string.uppercase, range(1, len(string.uppercase) + 1) ))

print letter_to_numeral
>>> {'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4, 'G': 7, 'F': 6, 'I': 9, 'H': 8, 'K': 11, 'J': 10, 'M': 13, 'L': 12, 'O': 15, 'N': 14, 'Q': 17, 'P': 16, 'S': 19, 'R': 18, 'U': 21, 'T': 20, 'W': 23, 'V': 22, 'Y': 25, 'X': 24, 'Z': 26}

def score_string(s):
    return sum([letter_to_numeral[character] for character in s])


score_string('ABC')
>>> 6

Enumerate can do the numbering for you:

import string
numerology_table = dict((ch,num+1) 
                         for (num,ch) in enumerate(string.ascii_letters[:26].upper()))

or even better, you can have enumerate start at 1 instead of the default of 0:

numerology_table = dict((ch,num) 
                         for (num,ch) in enumerate(string.ascii_letters[:26].upper(),
                                                   start=1))
def getvalue(mystring):
    letterdict = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ',range(1,27)))
    return sum(letterdict[c] for c in mystring)

If you are using Python3:

result = 0
mystring = 'ABC'
for char in mystring.encode('ascii'):
    result += char - 64

>>> result
6

Golfy answer certain to annoy your professor:

>>> s = 'ABC'
>>> sum(map(ord,s),-64*len(s))
6

The most sensible answer is of course using ord as shown earlier. But for those who chose to construct a dictionary, I would rather just use the index in the string:

>>> import string
>>> mystring = 'ABC'
>>> sum(string.uppercase.index(c) + 1 for c in mystring)
6

定义变量后,您只需返回答案或打印答案A = 1 B = 2 C = 3总计= A + B + C打印(总计)返回总计

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM