width = str(len(str(len(lines))))
The above monstrosity came up today while writing a function to add zero padded line numbers to a chunk of text:
def linenumbers(text):
"Add zero padded line numbers to text"
lines = text.split('\n')
# Find the maximum 'width' of the line count
width = str(len(str(len(lines))))
for i, line in enumerate(lines):
lines[i] = ("%0" + width + "d. %s") % (i + 1, line)
return '\n'.join(lines)
I think it has a pleasant kind of symmetry to it.
Why not just do
len(`len(lines)`)and/orlines[i] = ("%0%sd. %s") % (i + 1, width, line)?The former doesn't entail any surprises (
len()still returns an int) and you're already using string interpolation (is that the right term?) in the latter expression.Joe Grossberg - 10th February 2004 02:11 - #
Chris Vincent - 10th February 2004 02:18 - #
David Lindquist - 10th February 2004 04:47 - #
I'd write the guts of the function as:
Mark Russell - 10th February 2004 11:44 - #
string.zfill? Although I can't see a way around the len(str(len(lines))) construct. as Mark Russell mentions.sil - 10th February 2004 19:44 - #
The need for comments is a code smell. So I'll add another comment. ;)
How about:
Jeremy Dunck - 10th February 2004 22:12 - #
Not sure if those are the right function names, but that does the trick without multiple conversions, no?
Tom - 11th February 2004 15:13 - #
Tom's is better, as long as the reader is decent in math. ;)
Jeremy Dunck - 11th February 2004 16:10 - #
And proving once again that Perl is blatently superior to Python:
/me hides
(And yes,
length(@array)in Perl is equivalent tolen(str(len(array)))in Python. Isn't it great?)Ian Hickson - 14th February 2004 00:39 - #
If we assume *nix, and we assume the lines in question are contained in
somefile, and we assume that all we want to do is print the numbered lines to stdout or to some other file, why not:cat -n somefileI guess that is a lot of assuming though. :)
David Lindquist - 14th February 2004 22:48 - #
Ian, you don't want to use the prototype: it forces the argument(s) to scalar context.
Anyway, yet another way to do it that works with any type of line ending:
Or:
Or even:
Hmmm, maybe I got a bit carried away at the end there, but somehow it seemed appropriate...
Arien - 16th February 2004 10:12 - #
Mark - 25th March 2004 21:28 - #
Per - 16th December 2005 17:47 - #