Rochak Agrawal
Rochak Agrawal

Reputation: 87

How to Iterate over Alphabets in Python

Lets suppose a=0,b=1....,z=25,aa=26,...and so on.

How do I form a list in python to find the index for any given alphabet suppose ey?

book = xlrd.open_workbook(input("Enter name of the excel file "))
table_list=list(book.sheet_names())
print("the sheets in the excel file are :")
for name in table_list:
     print(name)
first_sheet = book.sheet_by_index(table_list.index(input("Enter sheet name ")))

arrayofvalues = first_sheet.col_values(152,2,239)

I need to use the obtained value in the col_val function.

Is there any other method?

Upvotes: 0

Views: 1341

Answers (1)

damisan
damisan

Reputation: 1047

It is a base-26 conversion, with a little twist (a works as a zero only at the rightmost place):

def col2idx(colname):
    colname = colname.lower()
    idx = 0
    for digit in colname:
        idx *= 26
        idx += ord(digit) - ord('a') + 1
    return idx - 1


print(col2idx('a'))  # == 0
print(col2idx('b'))  # == 1
print(col2idx('c'))  # == 2
print(col2idx('z'))  # == 25
print(col2idx('aa'))  # == 26
print(col2idx('ab'))  # == 27
print(col2idx('az'))  # == 51
print(col2idx('aij'))  # == 919
print(col2idx('amj'))  # == 1023
print(col2idx('zzad'))  # == 474581

Upvotes: 4

Related Questions