Pythonic way to create a long multi-line string

后端 未结 27 1643
滥情空心
滥情空心 2020-11-22 00:47

I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a +<

相关标签:
27条回答
  • 2020-11-22 00:52

    Generally, I use list and join for multi-line comments/string.

    lines = list()
    lines.append('SELECT action.enter code here descr as "action", ')
    lines.append('role.id as role_id,')
    lines.append('role.descr as role')
    lines.append('FROM ')
    lines.append('public.role_action_def,')
    lines.append('public.role,')
    lines.append('public.record_def, ')
    lines.append('public.action')
    query = " ".join(lines)
    

    you can use any string to join all this list element like '\n'(newline) or ','(comma) or ''(space)

    Cheers..!!

    0 讨论(0)
  • 2020-11-22 00:55

    Are you talking about multi-line strings? Easy, use triple quotes to start and end them.

    s = """ this is a very
            long string if I had the
            energy to type more and more ..."""
    

    You can use single quotes too (3 of them of course at start and end) and treat the resulting string s just like any other string.

    NOTE: Just as with any string, anything between the starting and ending quotes becomes part of the string, so this example has a leading blank (as pointed out by @root45). This string will also contain both blanks and newlines.

    I.e.,:

    ' this is a very\n        long string if I had the\n        energy to type more and more ...'
    

    Finally, one can also construct long lines in Python like this:

     s = ("this is a very"
          "long string too"
          "for sure ..."
         )
    

    which will not include any extra blanks or newlines (this is a deliberate example showing what the effect of skipping blanks will result in):

    'this is a verylong string toofor sure ...'
    

    No commas required, simply place the strings to be joined together into a pair of parenthesis and be sure to account for any needed blanks and newlines.

    0 讨论(0)
  • 2020-11-22 00:56

    Breaking lines by \ works for me. Here is an example:

    longStr = "This is a very long string " \
            "that I wrote to help somebody " \
            "who had a question about " \
            "writing long strings in Python"
    
    0 讨论(0)
  • 2020-11-22 00:56

    You can also concatenate variables in when using """ notation:

    foo = '1234'
    
    long_string = """fosdl a sdlfklaskdf as
    as df ajsdfj asdfa sld
    a sdf alsdfl alsdfl """ +  foo + """ aks
    asdkfkasdk fak"""
    

    EDIT: Found a better way, with named params and .format():

    body = """
    <html>
    <head>
    </head>
    <body>
        <p>Lorem ipsum.</p>
        <dl>
            <dt>Asdf:</dt>     <dd><a href="{link}">{name}</a></dd>
        </dl>
        </body>
    </html>
    """.format(
        link='http://www.asdf.com',
        name='Asdf',
    )
    
    print(body)
    
    0 讨论(0)
  • 2020-11-22 00:56

    I use a recursive function to build complex SQL Queries. This technique can generally be used to build large strings while maintaining code readability.

    # Utility function to recursively resolve SQL statements.
    # CAUTION: Use this function carefully, Pass correct SQL parameters {},
    # TODO: This should never happen but check for infinite loops
    def resolveSQL(sql_seed, sqlparams):
        sql = sql_seed % (sqlparams)
        if sql == sql_seed:
            return ' '.join([x.strip() for x in sql.split()])
        else:
            return resolveSQL(sql, sqlparams)
    

    P.S: Have a look at the awesome python-sqlparse library to pretty print SQL queries if needed. http://sqlparse.readthedocs.org/en/latest/api/#sqlparse.format

    0 讨论(0)
  • 2020-11-22 00:57

    If you don't want a multiline string but just have a long single line string, you can use parentheses, just make sure you don't include commas between the string segments, then it will be a tuple.

    query = ('SELECT   action.descr as "action", '
             'role.id as role_id,'
             'role.descr as role'
             ' FROM '
             'public.role_action_def,'
             'public.role,'
             'public.record_def, '
             'public.action'
             ' WHERE role.id = role_action_def.role_id AND'
             ' record_def.id = role_action_def.def_id AND'
             ' action.id = role_action_def.action_id AND'
             ' role_action_def.account_id = '+account_id+' AND'
             ' record_def.account_id='+account_id+' AND'
             ' def_id='+def_id)
    

    In a SQL statement like what you're constructing, multiline strings would also be fine. But if the extra whitespace a multiline string would contain would be a problem, then this would be a good way to achieve what you want.

    0 讨论(0)
提交回复
热议问题