iterating in reverse

Paul Rubin phr-n2003b at NOSPAMnightsong.com
Sat Jan 18 02:26:13 EST 2003


Nick Vargish <nav at adams.patriot.net> writes:
> > How about something like (untested):
> > 
> >     def convert(nbytes):
> >        suffixes = ['K', 'M', 'G', 'T', 'P', 'E']
> >        s = ''
> >        while nbytes >= 1024:
> >           nbytes /= 1024.0
> >           s = suffixes.pop(0)
> > 
> >        return '%.3f%c'% (nbytes, s)
> 
> It's supposed to look very spreadsheet-like, so I can't compress like
> that.

OK, here's another way, that I don't remember seeing in the thread
yet.  Maybe it's an improvement in the Pythonicness department over
your original scheme:

    def convert(nbytes):
      import re
      if nbytes == 0: return '0'
      if nbytes < 0: raise ValueError
      t = []
      while nbytes:
         nbytes, p = divmod(nbytes, 1000)
         t.insert(0, p)
      answer = ','.join([('%03d' % p) for p in t]) 
      return re.sub('^0+', '', answer)

Re setting the locale, I think code for that has been posted here
before.  Yeah, here's some:

   http://tinyurl.com/4l7z




More information about the Python-list mailing list