user3556962
user3556962

Reputation: 411

Convert numbers into corresponding letter using Python

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.

Upvotes: 38

Views: 102588

Answers (7)

ben
ben

Reputation: 71

Try a dict and some recursion:

import string

def Getletterfromindex(num):
    #produces a string from numbers so

    #1->a
    #2->b
    #26->z
    #27->aa
    #28->ab
    #52->az
    #53->ba
    #54->bb

    num2alphadict = dict(zip(range(1, 27), string.ascii_lowercase))
    outval = ""
    numloops = (num-1) //26
    
    if numloops > 0:
        outval = outval + Getletterfromindex(numloops)
        
    remainder = num % 26
    if remainder > 0:
        outval = outval + num2alphadict[remainder]
    else:
        outval = outval + "z"
    return outval

Upvotes: 7

LinconFive
LinconFive

Reputation: 2032

Big Letter:

chr(ord('@')+number)

1 -> A

2 -> B

...

Small Letter:

chr(ord('`')+number)

1 -> a

2 -> b

...

Upvotes: 66

khushbu
khushbu

Reputation: 164

for i in range(0, 100):
     mul = 1
     n   = i
     if n >= 26:
         n   = n-26
         mul = 2
     print chr(65+n)*mul

Upvotes: 1

vaultah
vaultah

Reputation: 46573

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

Upvotes: 18

Hugh Bothwell
Hugh Bothwell

Reputation: 56674

Here is a quick solution:

# assumes Python 2.7
OFFSET = ord("a") - 1

def letter(num):
    return chr(num + OFFSET)

def letters_sum_to(total):
    for i in xrange(1, min(total, 27)):
        for rem in letters_sum_to(total - i):
            yield [letter(i)] + rem
    if total <= 26:
        yield [letter(total)]

def main():
    for letters in letters_sum_to(8):
        print("".join(letters))

if __name__=="__main__":
    main()

which produces

aaaaaaaa
aaaaaab
aaaaaba
aaaaac
aaaabaa
aaaabb
aaaaca
aaaad
aaabaaa
# etc

Note that the number of solutions totalling to N is 2**(N-1).

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1123620

You can use chr() to turn numbers into characters, but you need to use a higher starting point as there are several other characters in the ASCII table first.

Use ord('a') - 1 as a starting point:

start = ord('a') - 1
a = chr(start + 1)

Demo:

>>> start = ord('a') - 1
>>> a = chr(start + 1)
>>> a
'a'

Another alternative is to use the string.ascii_lowercase constant as a sequence, but you need to start indexing from zero:

import string

a = string.ascii_lowercase[0]

Upvotes: 9

wflynny
wflynny

Reputation: 18541

What about a dictionary?

>>> import string
>>> num2alpha = dict(zip(range(1, 27), string.ascii_lowercase))
>>> num2alpha[2]
b
>>> num2alpha[25]
y

But don't go over 26:

>>> num2alpha[27]
KeyError: 27

But if you are looking for all alphabetical combinations of a given length:

>>> import string
>>> from itertools import combinations_with_replacement as cwr
>>> alphabet = string.ascii_lowercase
>>> length = 2
>>> ["".join(comb) for comb in cwr(alphabet, length)]
['aa', 'ab', ..., 'zz']

Upvotes: 8

Related Questions