在 Python 中将字母转换为数字 [英] Convert alphabet letters to number in Python

查看:82
本文介绍了在 Python 中将字母转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下如何完成?

characters = ['a''b''c''d''e''f''g''h''i''j''k''l''m''n''o''p''q''r''t''u''v''w''x''y''z']
numbers = ['1''2''3''4''5''6''7''8''9''10''11''12''13''14''15''16''17''18''19''20''21''22''23''24']
text = raw_input(' Write text: ')

我尝试了很多方法来解决它,但无法解决问题.我想做 exc.如果我输入你好",输出将是数字排列的字母表.示例 a = 1 <字母表.

I've tried to solve it many ways, but couldn't get to the pint. I want to make exc. If I type "hello" the output to be in numbers lined like in alphabet. Example a = 1 < in alphabet.

推荐答案

这样的事情怎么样:

print [ord(char) - 96 for char in raw_input('Write Text: ').lower()]

ord
列表理解
ASCII 字符代码

编辑
既然你要我解释,我会……尽管 [?] 在评论中已经解释得很好.

EDIT
Since you asked me to explain I will... though it has been explained pretty well in the comments already by [?].

让我们多一行开始.

input = raw_input('Write Text: ')
input = input.lower()
output = []
for character in input:
    number = ord(character) - 96
    output.append(number)
print output

这做同样的事情,但更具可读性.在尝试理解我的第一个答案之前,请确保您能够理解这里发生的事情.这里的一切都是非常标准的、简单的 Python.需要注意的一件事是 ord 函数.ord 代表 ordinal,几乎每种高级语言都有这种类型的函数可用.它为您提供了到任何字符的数字表示的映射.ord 的反函数称为 chr.

This does the same thing, but is more readable. Make sure you can understand what is going on here before you try to understand my first answer. Everything here is pretty standard, simple Python. The one thing to note is the ord function. ord stand for ordinal, and pretty much every high level language will have this type of function available. It gives you a mapping to the numerical representation of any character. The inverse function of ord is called chr.

chr(ord('x')) == 'x' # for any character, not just x.

如果你自己测试,a 的序数是 97(我在上面发布的第三个链接将显示完整的 ASCII 字符集.)每个小写字母都在 97-122(26 个字符)的范围内.所以,如果您只需从任何小写字母的序数中减去 96,假设您取 'a' == 1,您将得到它在字母表中的位置.因此,'b' == 98、'c' == 99 等的序数. 减去 96 时,'b' == 2,'c' == 3 等

If you test for yourself, the ordinal of a is 97 (the third link I posted above will show the complete ASCII character set.) Each lower case letter is in the range 97-122 (26 characters.) So, if you just subtract 96 from the ordinal of any lower case letter, you will get its position in the alphabet assuming you take 'a' == 1. So, ordinal of 'b' == 98, 'c' == 99, etc. When you subtract 96, 'b' == 2, 'c' == 3, etc.

我发布的初始解决方案的其余部分只是一些您可以学习的 Python 技巧,称为列表理解.但是,我不会像专注于学习用任何语言解决问题那样专注于此,其中 ord 是您的朋友.我希望这会有所帮助.

The rest of the initial solution I posted is just some Python trickery you can learn called list comprehension. But, I wouldn't focus on that as much as I would focus on learning to solve the problem in any language, where ord is your friend. I hope this helps.

这篇关于在 Python 中将字母转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆