iterating in reverse
Laura Creighton
lac at strakt.com
Fri Jan 17 13:46:17 EST 2003
> I just encountered a problem that required reverse iterating to solve,
> and my current solution, though it works, is not so satisfying:
>
> def commafy(val):
> """Return val as string with commas every thousandth place."""
> val = str(val)
> ret = ''
> c = 0
> for i in range(len(val) - 1, -1, -1):
> if c and not c % 3:
> ret = ',' + ret
> ret = val[i] + ret
> c += 1
> return ret
>
> This is one of the few times I just haven't been able to come up with
> an elegant and -- dare I say it -- aesthetically pleasing solution in
> Python. I suspect the lack is my own, not Python's.
>
> Nick
>
> --
> # sigmask.py || version 0.2 || 2003-01-07 || Feed this to your Python.
> print reduce(lambda x,y:x+chr(ord(y)-1),'Ojdl!Wbshjti!=obwAqbusjpu/ofu?','')
>
> --
> http://mail.python.org/mailman/listinfo/python-list
Well, you could reverse the string and operate on that, and then reverse
it back ...
Laura Creighton
More information about the Python-list
mailing list