ltrim on a block of text?
Bjorn Pettersen
BPettersen at NAREX.com
Fri May 11 16:01:29 EDT 2001
Say I have a variable
s = """
void f(int x) {
printf("%d\n", x);
}
"""
and I want to transform it to a list of lines L such that '\n'.join(L) would
give:
"""
void f(int x) {
printf("%d\n", x);
}
"""
i.e. I want to slice off the whitespace on the left of the entire block...
Is there a good way to do this?
My current approach seems a little fragile ;-)
def ltrimBlock(block):
"""Trim all the whitespace on the left of a block of text."""
txt = block.split('\n')
# the second line is more likely to contain the indentation
# we want to remove (if it is present).
if len(txt) > 2:
first = txt[1]
else:
first = txt[0]
count = 0
for c in first:
if c in ' \t':
count += 1
else:
break
return [ line[count:] for line in txt ]
-- bjorn
More information about the Python-list
mailing list