Python使用与Excel兼容的开始,结束字符获取范围

时间:2016-01-21 18:04:43

标签: python

如何使用alpha_range(A,ZZ)进行此操作?

  • 现在它只能工作到Z

代码:

def alpha_range(start, stop):
    """ Returns chars between start char and stop char(A,D -> A,B,C,D).
    :param start: start char
    :param stop: stop char
    :return: list of chars
    """
    return [chr(x) for x in range(ord(start), ord(stop)+1)]

1 个答案:

答案 0 :(得分:3)

您可以轻松地在A-ZZ和数字之间进行双向映射。这实际上非常类似于具有不同字符的数字系统来表示数字。

BASE = ord('Z') - ord('A') + 1

def to_number(str_input):
    res = 0
    for letter in str_input:
        res = res * BASE + ord(letter) - ord('A') + 1
    return res

def to_str(int_input):
    res = ''
    while int_input > 0:
        int_input -= 1
        res = res + chr(int_input % BASE + ord('A'))
        int_input //= BASE
    return res[::-1]

现在,您可以使用此功能替换ordchr