Convert Numbers into Corresponding Letter Using Python

Convert a number into its respective letter in the alphabet - Python 2.7

Although Your Question is not quite clear I wrote a script which do encryption using Dictionary

plaintext = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') #Alphabet String for Input
Etext = list('1A2B3C4D5E6F7G8H90IJKLMNOP') """Here is string combination of numbers and alphabets you can replace it with any kinda format and your dictionary will be build with respect to the alphabet sting"""

def messageEnc(text,plain, encryp):
dictionary = dict(zip(plain, encryp))
newmessage = ''
for char in text:
try:
newmessage = newmessage + dictionary[char.upper()]
except:
newmessage += ''
print(text,'has been encryptd to:',newmessage)

def messageDec(text,encryp, plain):
dictionary = dict(zip(encryp,plain))
newmessage = ''
for char in text:
try:

newmessage = newmessage + dictionary[char.upper()]

except:
newmessage += ''
print(text,'has been Decrypted to:',newmessage)


while True:
print("""
Simple Dictionary Encryption :
Press 1 to Encrypt
Press 2 to Decrypt
""")
try:
choose = int(input())
except:
print("Press Either 1 or 2")
continue

if choose == 1:

text = str(input("enter something: "))
messageEnc(text,plaintext,Etext)
continue
else:
text = str(input("enter something: "))
messageDec(text,Etext,plaintext)

How to convert numbers into their corresponding chronological english letters in python

You could use a dictionary that has the number as key and the letter as value. Then conversion can be done with [num]:

>>> import string

>>> translate_dict = dict(zip(range(1, 27), string.ascii_lowercase))

>>> translate_dict[2]
'b'

Using a dict to translate numbers to letters in python

Simply iterate through your alphabet string, and use a dictionary comprehension to create your dictionary

# Use a dictionary comprehension to create your dictionary
alpha_dict = {letter:idx for idx, letter in enumerate(alphabet)}

You can then retrieve the corresponding number to any letter using alpha_dict[letter], changing letter to be to whichever letter you want.

Then, if you want a list of letters corresponding to your num_list, you can do this:

[letter for letter, num in alpha_dict.items() if num in num_list]

which essentially says: for each key-value pair in my dictionary, put the key (i.e. the letter) in a list if the value (i.e. the number) is in num_list

This would return ['b', 'd', 'f'] for the num_list you provided



Related Topics



Leave a reply



Submit