ltrim on a block of text?

Bjorn Pettersen BPettersen at NAREX.com
Sun May 13 17:07:54 CEST 2001


Thanks a bunch!

-- bjorn

> -----Original Message-----
> From: Andrew Dalke [mailto:dalke at acm.org]
> Sent: Friday, May 11, 2001 7:01 PM
> To: python-list at python.org
> Subject: Re: ltrim on a block of text?
> 
> 
> 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
> 
> 
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 




More information about the Python-list mailing list