2016-01-21 48 views
2

如何使用alpha_range(A,ZZ)进行此项工作?Python获取范围使用与Excel兼容的开始,结束字符

  • 现在它只能工作到ž

代码:

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)] 
+0

你能提供一个示例输出吗? – gtlambert

+0

我不明白这个问题。 'alpha_range('A','ZZ')'的输出应该是什么样的? – timgeb

+0

@timgeb:我们需要一个像[Excel中的列标签]一样工作的字母范围(http://excelspreadsheet.net/images/yearlycalendar-004.jpg)。 – user2357112

回答

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这个功能。

+1

um,'to_number(“AA”)'返回'0',应该是'26','to_str(26)'返回'BA'。 –

+0

你说得对。将修复代码。 – nikihub

+2

太好了。为了使它与Python 3一起工作,使用'// ='而不是'/ ='。 –

相关问题