繁体   English   中英

如何取一个数字并找到它的字母位置python

[英]how to take a number and find its alphabet position python

到目前为止,我已经能够拿一封信并找到它的数字位置。 例如, a == 0但现在我想取那个数字,然后加上 4。然后返回该数字的等价字母。 所以, a == 0; 0 + 4 = 5; a == 0; 0 + 4 = 5; 应该返回f 因为它在字母表中排名第五! 到目前为止,这是我的代码:

def convert_int(str):
    a = string.lowercase.index(str)
    addition = a +13
    return addition;

使用chr()ord()函数。

print(ord('a'))  # 97
print(chr(97 + 4))  # e
print(chr(ord('f') + 2))  # h

最简单的方法是,你可以使用ord将 ascii 字符转换为十进制字符,例如: A ~ 65,然后你应该添加你想要的任何数字,然后使用chr将其转换回 ascii。 示例:

chr((ord(a) + number) % 123)

以更难的方式和流行的方式,你应该在 python 中使用dict

import string

alphabet=string.ascii_lowercase
#alphabet='abcdefghijklmnopqrstuvwxyz'

#print char by position: ex: 4 
 print(alphabet[4])
#This will print e 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM