python - 将数字字符串转换为字母python

标签 python

我需要将一串数字转换成一串字母来组成单词 例子: 如果程序的输入是 1920012532082114071825463219200125320615151209190846 它应该返回 保持饥饿。保持愚蠢。

到目前为止我有这个:

def number ():
output = []
input = raw_input ("please enter a string of numbers: ")
for number in input:
    if number <= 26:
        character = chr(int(number+96))
        output.append(character)
    else:
        character = chr(int(number))
        output.append(character)
print output

我需要它以某种方式确定每两个数字等于一个字母。 我有一个程序可以执行相反的操作,在给定字母时输出数字。这是它的样子:

def word ():
output = []
input = raw_input("please enter a string of lowercase characters: ")
for character in input:
    number = ord(character) - 96
    if number > 0:
        if number <= 9:
            output.append('0' + str(number))
        else:
            output.append(str(number))
    else:
        output.append(str(number + 96))
print ''.join(output)

感谢帮助

最佳答案

为您的输入字符串创建一个迭代器,并像这样调用 zip:

it = iter(data)
pairs = zip(it, it)

给予:

[('1', '9'), ('2', '0'), ('0', '1'), ('2', '5'), ('3', '2'), ('0', '8'), ('2', '1'), ('1', '4'), ('0', '7'), ('1', '8'), ('2', '5'), ('4', '6'), ('3', '2'), ('1', '9'), ('2', '0'), ('0', '1'), ('2', '5'), ('3', '2'), ('0', '6'), ('1', '5'), ('1', '5'), ('1', '2'), ('0', '9'), ('1', '9'), ('0', '8'), ('4', '6')]

接下来将其传递给带有 ''.join 的映射作为生成整数字符串的函数:

>>> map(''.join, zip(it,it))
['19', '20', '01', '25', '32', '08', '21', '14', '07', '18', '25', '46', '32', '19', '20', '01', '25', '32', '06', '15', '15', '12', '09', '19', '08', '46']

现在再次将其传递给映射,以转换为整数:

>>> map(int, map(''.join, zip(it,it)))
[19, 20, 1, 25, 32, 8, 21, 14, 7, 18, 25, 46, 32, 19, 20, 1, 25, 32, 6, 15, 15, 12, 9, 19, 8, 46]

现在将其传递给带有 lambda 的映射以执行解码逻辑:

>>> map(lambda n : chr(n+96) if n < 27 else chr(n), map(int, map(''.join, zip(it,it))))
['s', 't', 'a', 'y', ' ', 'h', 'u', 'n', 'g', 'r', 'y', '.', ' ', 's', 't', 'a', 'y', ' ', 'f', 'o', 'o', 'l', 'i', 's', 'h', '.']

最后,将 this 传递给 ''.join:

>>> ''.join(map(lambda n : chr(n+96) if n < 27 else chr(n), map(int, map(''.join, zip(it,it)))))
'stay hungry. stay foolish.'

还有什么可以更简单? :)

关于python - 将数字字符串转换为字母python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7720591/

相关文章:

python - 缺少输出,在 Python 中使用 range()

python - SublimeREPL 到 python

python - 对列表列表进行编码的优雅方式

python - 如何在python中的感兴趣区域周围绘制一个矩形

python - 变量参数与 Python 中的列表作为函数参数

python - 如何在 Python 中使用 Kerberos 库?

python - "logging"图片

python - 在 Python 中生成数字列表及其负数

python - 从网络开发转向桌面开发

python - 如何比较两个表并确定要返回的特定类型的行?