Hacker News new | past | comments | ask | show | jobs | submit login

    $ cat triple.py
    def foo():
        print """this is a triple quoted string
                 this is a continuation of a triple quoted string"""

    if __name__ == '__main__':
        foo()
    $ python triple.py
    this is a triple quoted string
                     this is a continuation of a triple quoted string
This is really warty. In bash you can mostly get around this with <<- for here documents (which removes leading indentation, so even if you're defining a here doc at a place that itself is indented, you don't have to align the text to the left column yourself). The man page in my version suggests it only works for leading tabs, not spaces, though.

e.g.

    $ function usage() {
            cat <<-END
                    this is a here document that
                    spans multiple lines and is indented
            END
    }
    $ usage
    this is a here document that
    spans multiple lines and is indented
    $



I don't have an opinion positive or negative on it, but since many other design decisions have already been mentioned, here is Haskell's design decision for multi-line string literals. It allows "tidy indenting", but like the first design decision, interacts badly with "reflowing / reformatting / filling".

http://book.realworldhaskell.org/read/characters-strings-and...


I'd normally write

    def foo():
        print """\
    this is a triple quoted string
    this is a continuation of a triple quoted string"""


    from __future__ import print_function
    import textwrap

    t = """
            Hello there
            This is aligned
    """

    # Need strip to get rid of extra NLs 

    print(textwrap.dedent(t).strip())


Use `textwrap.dedent()`?


Dedent is nice, but then you still have to deal with removing single newlines (e.g. for error messages) and removing leading and trailing spaces. Ultimately nothing more than `re.sub(r'[^\n]\n[^\n]', '', textwrap.dedent(s).strip())` but kind of annoying to have to throw this in your code all over the place.


Didn't know about textwrap, but this does not strike me as particularly lightweight. You really want built-in syntax for something like this.


I normally just do this for multiline strings:

    s = "\n".join(["one","two","three"])


This happens at run time whereas IIRC the string literal is crammed pre-joined into the ,pyc / .pyo file.

The performance hit of doing this kind of thing really adds up in a larger app.


I would put all messages in variables at the top of the file or even in a separate one and print them in the appropriate places.

Having multi line prints in functions add a lot of noise in my opinion. When i read code, i dont normally care about the content of messages being printed.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: