ltrim on a block of text?

Andrew Dalke dalke at acm.org
Fri May 11 21:01:19 EDT 2001


Bjorn Pettersen wants to turn
>s = """
>      void f(int x) {
>          printf("%d\n", x);
>      }
>"""

into

>"""
>void f(int x) {
>    printf("%d\n", x);
>}
>"""

The original string should likely be \\n because
otherwise the \n is embedded in the string.

Here's a function which does what you want

def ltrimBlock(s):
  lines = string.split(string.expandtabs(s), "\n")
  w = len(s)
  for line in lines:
    line2 = string.lstrip(line)
    if line2:
      w = min(w, len(line)-len(line2))
  new_lines = []
  for line in lines:
    new_lines.append(line[w:])
  return string.join(new_lines, "\n")

>>> print ltrimBlock("""
...     void f(int x) {
...             printf("%\\n", x);
...     }
...     int i = 4;
... """)

void f(int x) {
        printf("%\n", x);
}
int i = 4;

>>>

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list