sorting a list numbers stored as strings

thebjorn BjornSteinarFjeldPettersen at gmail.com
Tue Sep 25 18:55:21 CEST 2007


On Sep 25, 2:45 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Tue, 25 Sep 2007 12:46:54 +0800, Delaney, Timothy (Tim) wrote:
> > Carsten Haese wrote:
>
> >> On Mon, 2007-09-24 at 19:58 +0800, Delaney, Timothy (Tim) wrote:
> >>> I'm sure that in some version of Python it would have given a
> >>> ValueError (due to the default radix being 0) but it appears to have
> >>> changed to a default radix of 10 somewhere along the way.
>
> >> Not even Python 1.5.2 seems to have a problem with leading zeroes:
>
> >> Python 1.5.2 (#1, Nov  6 1999, 14:53:40) [C] on sco_sv3 Copyright
> >> 1991-1995 Stichting Mathematisch Centrum, Amsterdam
> >>>>> int("08")
> >> 8
>
> > Yep - appears I must have been misremembering from another language
> > (dunno which) or I misinterpreted the docs.
>
> I also remember something in Python about leading zeroes leading to
> "surprising" effects... ah, I got it!
>
> >>> int("020")
> 20
> >>> 020
> 16

You can get the latter behavior using eval:

>>> eval("020")
16
>>> eval("09")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    09
    ^
SyntaxError: invalid token
>>>

This usually bites you in the @$$ when you're trying to store config
data as a Python datastructure in an external file -- so that you can
do config_data = eval(open('config.data').read()).

-- bjorn




More information about the Python-list mailing list