Why do I require an "elif" statement here?

Tim Chase python.list at tim.thechases.com
Fri Aug 4 14:03:40 EDT 2006


> Could somebody tell me why I need the "elif char == '\n'" in
> the following code?
> 
> This is required in order the pick up lines with just spaces
> in them.
> Why doesn't the "else:" statement pick this up?

Following through with the below code:

if the line consists of only a newline, it gets ignored due to
the "if line[0] == whitespace" line. However, if the line
consists of only whitespace followed by a newline you *do*
successfully get to the "else" in question. There's no other
place for you to go.

However, what happens then? If you fall into you the top half of
your "if x > 0 ..." statement:

you strip **all** *true* whitespace from the line with your
lstrip() call. Since there's nothing between your "whitespace"
(simple spaces) and the \n, the \n gets swallowed by the lstrip()
call. Thus, you output.write() an empty string.

I recommend a few judiciously placed "print repr(thing)" lines as
you try to debug to see where things aren't what you expect them
to be.

As another sidelight, rather than using the "i=0, i+= 1" aspect, 
you can use the more pythonic idiom of

	for i, char in enumerate(line):

(taking into consideration that i becomes zero-based).  This will 
automatically update "i" on each pass.

-tkc

> 
> OLD_INDENT = 5  # spaces
> NEW_INDENT = 4  # spaces
> 
> print 'Reindent.py:'
> print '\nFrom file %s' % infile
> print 'Change %i space indentation to %i space indentation.' % (
>                                          OLD_INDENT, NEW_INDENT)
> print 'And place revised file into %s' % outfile
> 
> whitespace = ' '
> n = 0
> nline = 0
> 
> for line in input.readlines():
>     nline += 1
>     # Only look at lines that start with a space.
>     if line[0] == whitespace:
>         i = 0
>         for char in line:
>             i += 1
>             if char == whitespace:
>                 pass
>             elif char == '\n':          # Why do I need this for a
> blank line with only spaces?
>                 output.write(line)
>                 break
>             else:                        # Why doesn't the blank line
> get picked up here?
>                 x = line.count(whitespace*OLD_INDENT,0,i)
>                 # Reindent lines that have exactly a multiple of
> OLD_INDENT.
>                 if x > 0 and (i-1)%OLD_INDENT == 0:
>                     output.write(whitespace*NEW_INDENT*x+line.lstrip())
>                     n += 1
>                     break
>                 else:
>                     output.write(line)
>                     break
>     else:
>         output.write(line)
> 
> input.close()
> output.close()
> print 'Total number of %i lines reindented out of %i lines.' % (n,
> nline)
> 




More information about the Python-list mailing list