Why do I require an "elif" statement here?

Justin Azoff justin.azoff at gmail.com
Sun Aug 6 13:41:34 EDT 2006


danielx wrote:
> I'm surprised no one has mentioned neat-er, more pythonic ways of doing
> this. I'm also surprised no one mentioned regular expressions. Regular
> expressions are really powerful for searching and manipulating text.
[snip]

I'm surprised you don't count my post as a neat and pythonic way of
doing this.  I'm also surprised that you mention regular expressions
after neat and pythonic.  While regular expressions often serve a
purpose, they are rarely neat.

> Anyway, here's my solution, which does Not use regular expressions:
>
> def reindent(line):
>     ## we use slicing, because we don't know how long line is
>     head = line[:OLD_INDENT]
>     tail = line[OLD_INDENT:]
>     ## if line starts with Exactly so many spaces...
>     if head == whitespace*OLD_INDENT and not tail.startswith(' '):
>         return whitespace*NEW_INDENT + tail
>     else: return line    # our default
[snip]

This function is broken.  Not only does it still rely on global
variables to work, it does not actually reindent lines correctly.  Your
function only changes lines that start with exactly OLD_INDENT spaces,
ignoring any lines that start with a multiple of OLD_INDENT.

-- 
- Justin




More information about the Python-list mailing list