Simon Willison’s Weblog

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.

This is width = str(len(str(len(lines)))) by Simon Willison, posted on 10th February 2004.

Next: Code generation vs data driven programming

Previous: The dangers of PageRank

Previously hosted at http://simon.incutio.com/archive/2004/02/10/strlenstrlen