Code golf! Is there a simple way to convert letters to numbers in Python?

偶尔善良 提交于 2021-02-05 12:34:24

问题


You know, like A = 1, B = 2 etc. I could just make a long list of if-thens, but maybe there's already a module for it.

Bonus if it works like it does in "Excel Coordinates" where AA = 27 and continues. (Does this count as base26 numbers?)


回答1:


def foo(c):
    return ord(c) - 64

foo('A')

1

foo('B')

2

off the top of my head :p




回答2:


from string import ascii_uppercase
letterKey = dict(list(zip( ascii_uppercase, range(1, 27))))

And as for the excel cords:

geExceltValue = lambda string: sum([26**i * list(reversed(map(lambda x: letterKey[x], string)))[i] for i in range(len(string))])

print geExceltValue("AA")


来源:https://stackoverflow.com/questions/29104338/code-golf-is-there-a-simple-way-to-convert-letters-to-numbers-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!