使用 Python 将数字转换为相应的字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23199733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:28:31  来源:igfitidea点击:

Convert numbers into corresponding letter using Python

pythonpython-3.xnumericalalphabetical

提问by user3556962

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.

看我知道如何构建程序的其余部分,除了这个!任何帮助都会很棒。

回答by vaultah

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

回答by Martijn Pieters

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.

您可以使用chr()将数字转换为字符,但您需要使用更高的起点,因为 ASCII 表中还有其他几个字符。

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

使用ord('a') - 1为出发点:

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_lowercaseconstantas a sequence, but you need to start indexing from zero:

另一种方法是使用string.ascii_lowercase常数作为一个序列,但你需要从开始索引

import string

a = string.ascii_lowercase[0]

回答by running gherkin

If you just want to map between letters and numbers in your own way, Dictionaryis what you should look at.

如果您只想以自己的方式在字母和数字之间进行映射,那么您应该查看字典

回答by wflynny

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:

但不要超过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']

回答by Hugh Bothwell

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).

请注意,总计为 N 的解数为 2**(N-1)。

回答by khushbu

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

回答by LinconFive

Big Letter:

大信:

chr(ord('@')+number)

1 -> A

1 -> A

2 -> B

2 -> 乙

...

...

Small Letter:

很小的字:

chr(ord('`')+number)

1 -> a

1 -> 一个

2 -> b

2 -> 乙

...

...

回答by ben

Try a dict and some recursion:

尝试一个 dict 和一些递归:

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