multiline strings and proper indentation/alignment

bruno at modulix onurb at xiludom.gro
Wed May 10 06:43:47 EDT 2006


John Salerno wrote:
> Gary Herron wrote:
> 
>> Gary John Salerno wrote:
>>
>>> How do you make a single string span multiple lines, but also allow
>>> yourself to indent the second (third, etc.) lines so that it lines up
>>> where you want it, without causing the newlines and tabs or spaces to
>>> be added to the string as well?
>>>
>>> Example (pretend this is all on one line):
>>>
>>> self.DTD = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML
>>> 4.01//EN"\n"http://www.w3.org/TR/html4/strict.dtd">\n\n'
>>>
>>> I want it to read:
>>>
>>> self.DTD = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"\n
>>>            "http://www.w3.org/TR/html4/strict.dtd">\n\n'''
>>>
>>> Or anything like that, but I don't want the extra newline or tabs to
>>> be a part of the string when it's printed.
>>>
>>> Thanks.
>>>  
>>>
>> The textwrap module has a function to do just the thing you want. 
>> *dedent*(     text)
>>
>>     Remove any whitespace that can be uniformly removed from the left of
>>     every line in text.
>>
>>                 This is typically used to make triple-quoted strings
>>     line up with the left edge of screen/whatever, while still
>>     presenting it in the source code in indented form.
>>
>> Gary Herron
>>
>>
> 
> But does this do anything to the newline character that gets added to
> the end of the first line?

Why not trying by yourself ?-)
>>> import textwrap
>>> s = """
...     this is a multiline
...     triple-quted string with
...     indentation for nicer code formatting
... """
>>> print s

    this is a multiline
    triple-quted string with
    indentation for nicer code formatting

>>> print textwrap.dedent(s)

this is a multiline
triple-quted string with
indentation for nicer code formatting

>>>

Obviously, you have to strip newlines yourself. Let's try:
>>> print textwrap.dedent(s.strip())
this is a multiline
    triple-quted string with
    indentation for nicer code formatting

Mmm. Not good. Let's try again:
>>> print textwrap.dedent(s).strip()
this is a multiline
triple-quted string with
indentation for nicer code formatting
>>>

Well, seems like we're done. About 2'30'' to solve the problem.

FWIW, reading textwrap's doc may be useful to - no need to reinvent the
SquaredWheel(tm) if the rounded version already exists !-)

HTH
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list