question about the textwrap module

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Oct 27 19:45:03 EDT 2008


En Mon, 27 Oct 2008 20:50:08 -0200, TP <Tribulations at paralleles.invalid>  
escribió:

> Recently, I have tried to improve the look of the printed text in command
> line. For this, I was compelled to remove redundant spaces in strings,
> because in my scripts, often the strings are spreading on several lines.
>
> For example, "aaa   bbb" had to be transformed in "aaa bbb".
> I have coded some simple functions to do that.
>
> Today, by examining Python documentation, I have found an interesting
> module:
>
> http://www.python.org/doc/2.5.2/lib/module-textwrap.html
>
> But, I haven't found any way to do my redundant space deletion with this
> module? Am I right?

You may pre-process your text (stripping redundant whitespace) before  
using textwrap:

py> text = 'This          is some \t   text with  multiple\n\n  spaces.'
py> print textwrap.fill(text, width=20)
This          is
some      text with
multiple    spaces.
py> import re
py> re.sub(r'\s+', ' ', text)
'This is some text with multiple spaces.'
py> t2 = _
py> print textwrap.fill(t2, width=20)
This is some text
with multiple
spaces.
py>

-- 
Gabriel Genellina




More information about the Python-list mailing list