Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numbers into corresponding letter using Python

Tags:

I was wondering if it is possible to convert numbers into their corresponding alphabetical value. So

1 -> a 2 -> b 

I was planning to make a program which lists all the alphabetical combinations possible for a length specified by a user.

See I know how to build the rest of the program except this! Any help would be wonderful.

like image 306
user3556962 Avatar asked Apr 21 '14 14:04

user3556962


People also ask

How will you convert an integer to an Unicode character in Python?

unichr() is named chr() in Python 3 (conversion to a Unicode character).


2 Answers

Big Letter:

chr(ord('@')+number) 

1 -> A

2 -> B

...

Small Letter:

chr(ord('`')+number) 

1 -> a

2 -> b

...

like image 120
LinconFive Avatar answered Sep 25 '22 19:09

LinconFive


import string for x, y in zip(range(1, 27), string.ascii_lowercase):     print(x, y) 

or

import string for x, y in enumerate(string.ascii_lowercase, 1):     print(x, y) 

or

for x, y in ((x + 1, chr(ord('a') + x)) for x in range(26)):     print(x, y) 

All of the solutions above output lowercase letters from English alphabet along with their position:

1 a ... 26 z 

You'd create a dictionary to access letters (values) by their position (keys) easily. For example:

import string d = dict(enumerate(string.ascii_lowercase, 1)) print(d[3]) # c 
like image 36
vaultah Avatar answered Sep 24 '22 19:09

vaultah