Why do I require an "elif" statement here?

sp1d3rx at gmail.com sp1d3rx at gmail.com
Fri Aug 4 14:08:22 EDT 2006


Jim, what you wrote should work correctly. I'm curious as to why you
are doing it this way though. An easier way would be to take out all
this character processing and use the builtin string processing. See
this code:

-------------------------------
whitespace = " "
old_indent = 3
new_indent = 5

x = "   starts with 3 spaces"

x = x.replace(whitespace*old_indent, whitespace*new_indent)
-------------------------------

In this example though, it will replace the 3 spaces no matter where
they are at, not just in the beginning... still, it's probably more
practical for most use cases.


Jim wrote:
> 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?
>
> 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