What is the proper indentation for Python multiline strings within a function?
def method(): string = """line one line two line three"""
or
def method(): string = """line one line two line three"""
or something else?
It looks kind of weird to have the string hanging outside the function in the first example.
Use triple quotes to create a multiline string You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.
So, Python code structures by indentation. Note: Python uses 4 spaces as indentation by default. However, the number of spaces is up to you, but a minimum of 1 space has to be used.
If you prefer using [spacebar] to indent your code rather than using [tab], you can select multiple lines by holding the [alt] key and clicking on the beginning of each line you want to indent. Then, you can press [spacebar] and all the selected lines will be affected. omg it moves!
Every code editor worth its salt has a one-key way to indent and dedent blocks. In IDLE (the IDE included with Python), CTRL + [ dedents and CTRL + ] indents. Selecting text then using the shift+tab shortcut also works if you're using the Python editor built into Canopy on Windows.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With