danielx wrote: > No offense. I didn't mean there was anything wrong with your way, just > that it wasn't "neat". By that, I meant, you were still using lots of > for loops and if blocks. > > Justin Azoff wrote: > > 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. > > I suppose I put those things too close together. I meant I was > surprised for each of the two Separate (non)occurances.
And what would regexes give you? A Pythonic way of calculating the number of leading spaces??? N.B. in your (mis)reading of the OP's intent, you don't need/use the number of leading spaces. > > > > > 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 > > It's just an illustration. An illustration of ... what? > > > function only changes lines that start with exactly OLD_INDENT spaces, > > ignoring any lines that start with a multiple of OLD_INDENT. > > Maybe I misread, but that's what I thought he wanted. (a) Such a requirement is rather implausible. (b) No "maybe": 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()) > Did you not see > my code comments expressing that very intent? Those comments merely documented the brokenness. > Anyway, it wouldn't be > that hard to modify what I gave to do multiple replacement: just add a > recursive call. ... which would make it uglier. -- http://mail.python.org/mailman/listinfo/python-list