简体   繁体   中英

Associate letters and numbers, and calculate sum of string in Python

I am currently learning Python for a while and made a program called character counter ; which you input a text/word and it prints out a number eg abc = 6 because a = 1 , b = 2 , c = 3 and so on.

And I found out while coding, it took me very long because I had to assign values to each alphabet (like the examples I showed before) and the whole thing took more than 80 lines.

Is there any way I could simplify this?

alpha = str(input('enter something '))
i = 0

beta = list(alpha)
z = len(beta)


while z > 0:
    if beta[i] == "a":
        beta[i] = 1

    if beta[i] == 'b':
        beta[i] = 2

    if beta[i] == 'c':
        beta[i] = 3

    if beta[i] == "d":
        beta[i] = 4

    if beta[i] == 'e':
        beta[i] = 5

    if beta [i] == 'f':
         beta[i] = 6 

    if beta[i] == 'g':
        beta[i] = 7

    if beta[i] == 'h':
        beta[i] = 8
    
    if beta[i] == 'i':
        beta[i] = 9

    if beta[i] == 'j':
        beta[i] = 10
    
    if beta[i] == 'k':
        beta[i] = 11
    
    if beta[i] == 'l':
        beta[i] = 12
    
    if beta[i] == 'm':
        beta[i] = 13

    if beta[i] == 'n':
        beta[i] = 14

    if beta[i] == 'o':
        beta[i] = 15

    if beta[i] == 'p':
        beta[i] = 16

    if beta[i] == 'q':
        beta[i] = 17

    if beta[i] == 'r':
        beta[i] = 18
    
    if beta[i] == 's':
        beta[i] = 19

    if beta[i] == 't':
        beta[i] = 20

    if beta[i] == 'u':
        beta[i] = 21
    
    if beta[i] == 'v':
        beta[i] = 22

    if beta[i] == 'w':
        beta[i] = 23
    
    if beta[i] == 'x':
        beta[i] = 24
    
    if beta[i] == 'y':
        beta[i] = 25
    
    if beta[i] == 'z':
        beta[i] = 26


    i= i + 1
    z = z - 1

print(sum(beta))

I think that there should be a simpler way of writing it, but I currently dont know how.

The 'condensed' way of writing what you have is to put them all in a dict:

mapping = {
    'a': 1,
    'b': 2,
    ...
    'z': 26
}

...

while z > 0:
    beta[i] = mapping[beta[i]]
    i = i + 1
    z = z - 1

The ideal way, though, is to construct the dict in a single line, dynamically:

from string import ascii_lowercase
# ascii_lowercase == 'abcdefghijklmnopqrstuvwxyz'
# see also https://docs.python.org/3/library/string.html

mapping = dict(zip(ascii_lowercase, range(1, 27)))
# range(1, 27) yields (1, 2, ..., 25, 26)
# zip() will yield 2-tuples between corresponding elements, a=1, b=2, ..., z=26
# dict() can take a list of 2-tuples, and interpret them as keys and values respectively

You can use some utils such as enumerate , string.ascii_lowercase , and sum :

from string import ascii_lowercase as low

num = {c: i for i, c in enumerate(low, 1)}

def total(alpha):
    return sum(num[char] for char in alpha)

>>> total("abc")
6
>>> total("abcd")
10

An easy way to do this would be to use the ord() function

Unicode characters have an integer associated with them that we can get using ord(character)

letters az go from 97 to 122

So you could do something like this

def counter():

    letters = input("whatever")

    # incase non letters passed
    if not letters.isalpha():
        return "not letters"

    output = 0
    for letter in letters.lower():
        output += ord(letter) - 96

    return output

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