I want sequence like excel headers.
e.g : A,B,C,..,Z,AA,AB....
My code
>>> s = 'A'
>>> chr(ord(s) + 1)
'B'
>>> s = 'Z'
>>> chr(ord(s) + 1)
'['
>>>
# I want AA after chr(ord('Z') + 1)
I want sequence like excel headers.
e.g : A,B,C,..,Z,AA,AB....
My code
>>> s = 'A'
>>> chr(ord(s) + 1)
'B'
>>> s = 'Z'
>>> chr(ord(s) + 1)
'['
>>>
# I want AA after chr(ord('Z') + 1)
using itertools,
import itertools
alpha = [chr(x) for x in range(65, 91)] # create a list of character's
print(alpha + [k + v for k,v in itertools.product(alpha, repeat=2)])
You can trying this:
def get_colnum_string(n):
string = ""
while n > 0:
n, remainder = divmod(n - 1, 26)
string = chr(65 + remainder) + string
return string
>>> get_colnum_string(1)
'A'
>>> get_colnum_string(26)
'Z'
>>> get_colnum_string(27)
'AA'
>>>
Suppose you want to go "n deep", meaning that you want your last header to have n letters:
import itertools
import string
def generateHeaders(n=None):
if n is None: nums = itertools.count(1)
else: nums = range(1, n+1)
for n in nums:
yield from map(''.join, itertools.product(*([string.ascii_uppercase]*n)))
Output testing:
for _,header in zip(range(60), generateHeaders()): print(header)
A
B
C
D
E
F
G
H
I
J
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
Y
Z
AA
AB
AC
AD
AE
AF
AG
AH
AI
AJ
AK
AL
AM
AN
AO
AP
AQ
AR
AS
AT
AU
AV
AW
AX
AY
AZ
BA
BB
BC
BD
BE
BF
BG
BH
Simplely you may create a list to contain the sequance. It's simple but not good enough. e.g.
seq = ['A', 'B', ... 'ZZ']
s = 'A' # s.toupper() if required.
idx = seq.index(s)
if idx < 0:
print('not in sequence')
return # or exit
next = idx + 1
if next >= len(seq):
next = 0
print(seq[next])