[Tutor] Recording and eliminating continuation lines
Brad Reisfeld
brad.reisfeld@colostate.edu
Thu Nov 7 07:39:02 2002
Magnus Lycka wrote:
> Do one thing at a time!
>
> >>> text = r'''first row ends
> ... second row continued \
> ... third row continued \
> ... fourth row ends.
> ... Fifth row by itself.'''
> >>> rowList = [[]]
> >>> physRow = 1
> >>> for row in text.split('\n'):
> ... rowList[-1].append(physRow)
> ... physRow += 1
> ... if not row.endswith('\\'):
> ... rowList.append([])
> ...
> >>> rowList
> [[1], [2, 3, 4], [5], []]
> >>> text = text.replace('\\\n','')
> >>> result = zip(rowList, text.split('\n'))
> >>> import pprint
> >>> pprint.pprint(result)
> [([1], 'first row ends'),
> ([2, 3, 4], 'second row continued third row continued fourth row
ends.'),
> ([5], 'Fifth row by itself.')]
>
> If you feel it's important you can do a
> rowList = map(tuple, rowList)
> before the zip.
Thank you for the suggestion.
However, I think that in this case, it is better programming practice to do
the line concatenation and physical line accounting in the same step. Using
two different steps for these operations has a higher probability of getting
things out of sync.
Regards,
Brad