[Tutor] Out of range

Jeff Shannon jeff@ccvcorp.com
Tue Feb 4 17:51:34 2003


Adam Vardy wrote:

>This function tries to adapt the prefix somewhere so the whole thing
>will sort properly.
>  
>

As Magnus already pointed out, the only way to get an IndexError here is 
if you pass in an empty string.  I'd also guess, though, that the 
results of this function are not quite what you're expecting.  (By the 
way, it's not necessary to comapre your isdigit() and isalpha() results 
explicitly with 1 and 0, nor is it considered good style...)

 >>> def fixit(text):
...     index = 0
...     if not text[0].isdigit():
...         return text
...     for i in text:
...         if i.isalpha():
...             break
...         index = index + 1
...     out = text[index]
...     num = text[:index]
...     rest = text[index:]
...     return out + num + rest
...
 >>> fixit('testing')
'testing'
 >>> fixit('1-2-testing')
't1-2-testing'
 >>> fixit('1234abcd')
'a1234abcd'
 >>>

Note that 'text[index]' will be the first non-digit character, 
'text[:index]' will be the initial run of digits, and 'text[index:]' 
will be everything after the initial run of digits.  Adding these 
together gives you your initial string, prepended by the first non-digit 
character.  If we don't add them together, and instead return a tuple:

 >>> def fixit(text):
...     index = 0
...     if text[0].isdigit() == 0:
...         return text
...     for i in text:
...         if i.isalpha() == 1:
...             break
...         index = index + 1
...     out = text[index]
...     num = text[:index]
...     rest = text[index:]
...     return out, num, rest
...
 >>>

Note that the only line I've changed is the return statement.  Our 
results are much different now:

 >>> fixit('1234abcd')
('a', '1234', 'abcd')
 >>> fixit('1.5Meg')
('M', '1.5', 'Meg')
 >>> fixit('1-2-testing')
('t', '1-2-', 'testing')
 >>> fixit('123abc456')
('a', '123', 'abc456')
 >>>

So the part we're returning as 'num' is now the initial numeric part, 
and 'rest' is indeed the rest of it.  Since I presume you're wanting to 
use this to sort items in numeric order, you then need to convert the 
string of digits into an actual number, so that they're compared in 
numeric order instead of lexicographic order.

For ideas on what to do with 'num' and 'rest' now that you've got them 
separated, see my previous reply on 'Sorting Numbers'.

Jeff Shannon
Technician/Programmer
Credit International