Home > Software design >  How to convert alphabetical input to numbers and add them together
How to convert alphabetical input to numbers and add them together

Time:11-09

i'm trying to convert user input into only alphabets, and convert each alphabet into a number(ex. a=1, b=2), then the numbers together. I've been able to complete the first part, but not sure how to do the second part.

import re
name = input("Name: ")
cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)
numbers = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,
       'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
for al in range(len(cleaned_name)):
    print(numbers,sep=' ')

#if input is jay1joe2, cleaned name will be jayjoe
#after the 'numerology', will print the following below
#10 1 25 10 15 5 = 66

CodePudding user response:

Something like this should work for what you're trying to do.

Note: I'm hardcoding the name here rather than using the user input, so it's easier to test it out if needed.

import string

# name = input("Name: ")
name = 'jay1joe2'

cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)

numbers = {char: i for i, char in enumerate(string.ascii_lowercase, start=1)}

result = list(map(numbers.get, cleaned_name))
print(*result, sep=' ', end=' ')
print('=', sum(result))

Where the second part (after numbers) could also be written alternatively as follows, using f-strings in 3.6 :

result = [numbers[c] for c in cleaned_name]
print(f"{' '.join(map(str, result))} = {sum(result)}")

Result:

Your 'cleaned up' name is:  jayjoe
10 1 25 10 15 5 = 66

CodePudding user response:

name = input("Name: ")
name = name.lower()
name1 = list(name)
Addition: int = 0
for k in name1:
    if ord(k)-96 < 1 or ord(k)-96 > 26:
        pass
    else:
        Addition = Addition   ord(k) - 96
print(Addition)

We can use ascii codes for Numbers and Characters :)

CodePudding user response:

firstly an easier way to find the "number" value of a string would be to have one long string with all the letters of the alphabet ie: numbers = "abcd..." and then to find the "spot" of a given letter you could do number.find(letter).

for the second part I would use a for loop so

number_name = ""
numbers = " abcdefghijklmnopqrstuvwxyz"
for letter in cleaned_name:
    number_name  = str(number.find(letter))   " "
number_name = number_name[:-1] # to remove the extra   at the end
print(number_name)

`

  • Related