Convert from numbers to letters
Mike Meyer
mwm at mired.org
Thu May 19 16:40:38 EDT 2005
Bill Mill <bill.mill at gmail.com> writes:
> On 19 May 2005 11:59:00 -0700, rh0dium <sklass at pointcircle.com> wrote:
>> This is great but backwards...
>>
>> Ok because you all want to know why.. I need to convert Excel columns
>> A2 into , [1,0] and I need a simple way to do that..
>>
>> ( The way this works is A->0 and 2->1 -- Yes they interchange -- So
>> B14 == [13,1] )
>
> why didn't you say this in the first place?
>
> def coord2tuple(coord):
> row, col = '', ''
> alpha = 'abcdefghijklmnopqrstuvwxyz'.upper()
> pairs = [''.join((x,y)) for x in alpha for y in [''] + [z for z in alpha]]
> pairs = sorted(pairs, key=len)
> coord = coord.upper()
> for c in coord:
> if c in alpha:
> row += c
> else:
> col += c
> return (int(col)-1, pairs.index(row))
That seems like the long way around. Python can search strings for
substrings, so why not use that? That gets the search loop into C
code, where it should be faster.
from string import uppercase
def coord2tuple2(coord):
if len(coord) > 1 or uppercase.find(coord) < 0:
raise ValueError('coord2tuple2 expected a single uppercase character, got "%s"' % coord)
return uppercase.index(coord) + 1
Without the initial test, it has a buglet of return values for "AB"
and similar strings. If searching uppercase twice really bothers you,
you can drop the uppercase.find; then you'll get less informative
error messages if coord2tuple2 is passed single characters that aren't
in uppercase.
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list