使用Python将数字转换为对应字母

36 投票
7 回答
92885 浏览
提问于 2025-04-18 03:36

我在想,是否可以把数字转换成对应的字母值。比如说,

1 -> a
2 -> b

我打算做一个程序,列出用户指定长度的所有字母组合。

你看,我知道怎么做这个程序的其他部分,就是这一块不太清楚!如果能帮忙就太好了。

7 个回答

6

试试用字典和递归的方法:

def Getletterfromindex(self, 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 + self.Getletterfromindex(numloops)

    remainder = num % 26
    if remainder > 0:
        outval = outval + num2alphadict[remainder]
    else:
        outval = outval + "z"
    return outval
8

字典怎么样呢?

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

不过别超过26个:

>>> num2alpha[27]
KeyError: 27

如果你想找出某个长度的所有字母组合:

>>> 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']
9

你可以使用 chr() 这个函数把数字转换成字符,不过要注意,ASCII表里有很多其他字符,所以你得从一个更高的数字开始。

可以用 ord('a') - 1 作为起始点:

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

示例:

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

另外一种方法是使用 string.ascii_lowercase 常量,把它当作一个序列来用,但你需要从 开始索引:

import string

a = string.ascii_lowercase[0]
18
import string
for x, y in zip(range(1, 27), string.ascii_lowercase):
    print(x, y)

或者

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

或者

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

上面所有的解决方案都会输出英文字母的小写字母以及它们的位置:

1 a
...
26 z

你可以创建一个字典,这样就能通过位置(键)轻松访问字母(值)。比如:

import string
d = dict(enumerate(string.ascii_lowercase, 1))
print(d[3]) # c
60

大写字母:

chr(ord('@')+number)

1 -> A

2 -> B

...

小写字母:

chr(ord('`')+number)

1 -> a

2 -> b

...

撰写回答