Proper Indentation for Multiline Strings

Proper indentation for multiline strings?

You probably want to line up with the """

def foo():
string = """line one
line two
line three"""

Since the newlines and spaces are included in the string itself, you will have to postprocess it. If you don't want to do that and you have a whole lot of text, you might want to store it separately in a text file. If a text file does not work well for your application and you don't want to postprocess, I'd probably go with

def foo():
string = ("this is an "
"implicitly joined "
"string")

If you want to postprocess a multiline string to trim out the parts you don't need, you should consider the textwrap module or the technique for postprocessing docstrings presented in PEP 257:

def trim(docstring):
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)

Indentation when using multi-line strings

Wrap the string in a call to inspect.cleandoc and it will clean it up the same way docstrings get cleaned up (removing leading and trailing whitespace, and any level of common indentation).

>>> import inspect
>>> s = """jkljkj
... dfkjslfds
... sqjdlqkj"""
...
>>> print(s)
jkljkj
dfkjslfds
sqjdlqkj
>>> s = inspect.cleandoc(s)
>>> print(s)
jkljkj
dfkjslfds
sqjdlqkj

textwrap.dedent is also an option, but it's uglier, as it requires you to put no text on the first line, and explicitly use a line continuation character to ensure every line (not just the second and onwards) has identical leading indentation:

>>> print(textwrap.dedent('''\
... The^backslash is a pain
... so I don't recommend this approach
... '''))
The^backslash is a pain
so I don't recommend this approach

Note that while code blocks on SO don't show it properly, dedent left the empty final line (from putting the closing ''' on a line by itself), where cleandoc would have removed it.

How to indent the contents of a multi-line string?

Why not pipe the output through a command-line code formatter such as astyle?

indentation of multiline string

Personally I try to follow PEP 8 which refers the reader to PEP 257 for Docstring Conventions. It has an entire section on multi-line docstrings.

Acting on the indentation of a c# multiline string

You could wrap the string to the next line to get the desired indentation:

    string div = 
@"
<div class=""className"">
<span>Mon text</span>
</div>"
.TrimStart(); // to remove the additional new-line at the beginning

Another nice solution (disadvantage: depends on the indentation level!)

        string div = @"
<div class=""className"">
<span>Mon text</span>
</div>".TrimStart().Replace("\n ", "\n");

It just removes the indentation out of the string. make sure the number of spaces in the first string of the Replace is the same amount of spaces your indentation has.

indentation style for multi-line string literals

Considering both propositions would add newline or spaces to the litteral string, I would favor (even though fmt format the first line):

    select, err = db.Prepare(
`select name
from table
where id=$1`)

As the OP akonsu comments below, it seems consistent with the style of the golang code itself, as seen in src/cmd/go/main.go#L175, which keeps the first line at the level of the opening '('

var usageTemplate = `Go is a tool for managing Go source code.
Usage:
go command [arguments]
...
`


Related Topics



Leave a reply



Submit