Pythonic way to create a long multi-line string

后端 未结 27 1682
滥情空心
滥情空心 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 01:12

    "À la" Scala way (but I think is the most pythonic way as OQ demands):

    description = """
                | The intention of this module is to provide a method to 
                | pass meta information in markdown_ header files for 
                | using it in jinja_ templates. 
                | 
                | Also, to provide a method to use markdown files as jinja 
                | templates. Maybe you prefer to see the code than 
                | to install it.""".replace('\n            | \n','\n').replace('            | ',' ')
    

    If you want final str without jump lines, just put \n at the start of the first argument of the second replace:

    .replace('\n            | ',' ')`.
    

    Note: the white line between "...templates." and "Also, ..." requires a whitespace after the |.

    0 讨论(0)
  • 2020-11-22 01:13

    This approach uses:

    • just one backslash to avoid an initial linefeed
    • almost no internal punctuation by using a triple quoted string
    • strips away local indentation using the textwrap inspect module
    • uses python 3.6 formatted string interpolation ('f') for the account_id and def_id variables.

    This way looks the most pythonic to me.

    # import textwrap  # See update to answer below
    import inspect
    
    # query = textwrap.dedent(f'''\
    query = inspect.cleandoc(f'''
        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}'''
    )
    

    Update: 1/29/2019 Incorporate @ShadowRanger's suggestion to use inspect.cleandoc instead of textwrap.dedent

    0 讨论(0)
  • 2020-11-22 01:14

    Another option that I think is more readable when the code (e.g variable) is indented and the output string should be a one liner (no newlines):

    def some_method():
    
        long_string = """
    a presumptuous long string 
    which looks a bit nicer 
    in a text editor when
    written over multiple lines
    """.strip('\n').replace('\n', ' ')
    
        return long_string 
    
    0 讨论(0)
  • 2020-11-22 01:14

    Combining the ideas from:

    Levon or Jesse, Faheel and ddrscott

    with my formatting suggestion, you could write your query as:

    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
             )
    
     vars = (account_id, account_id, def_id)     # a tuple of the query variables
     cursor.execute(query, vars)                 # using Python's sqlite3 module
    

    or like:

    vars = []
    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 = '
                     vars.append(account_id) or '?'
                 ' AND'
                 ' record_def.account_id = '
                     vars.append(account_id) or '?'
                 ' AND'
                 ' def_id = '
                     vars.append(def_id) or '?'
             )
    
     cursor.execute(query, tuple(vars))  # using Python's sqlite3 module
    

    Which could be interesting together with 'IN' and 'vars.extend(options) or n_options(len(options))', where:

    def n_options(count):
        return '(' + ','.join(count*'?') + ')'
    

    Or with the hint from darkfeline, that you might still make mistakes with those leading spaces and separators and also with named placeholders:

    SPACE_SEP = ' '
    COMMA_SEP = ', '
    AND_SEP   = ' AND '
    
    query = SPACE_SEP.join((
        'SELECT',
            COMMA_SEP.join((
            'action.descr as "action"',
            'role.id as role_id',
            'role.descr as role',
            )),
        'FROM',
            COMMA_SEP.join((
            'public.role_action_def',
            'public.role',
            'public.record_def',
            'public.action',
            )),
        'WHERE',
            AND_SEP.join((
            'role.id = role_action_def.role_id',
            'record_def.id = role_action_def.def_id',
            'action.id = role_action_def.action_id',
            'role_action_def.account_id = :account_id',
            'record_def.account_id = :account_id',
            'def_id = :def_id',
            )),
        ))
    
    vars = {'account_id':account_id,'def_id':def_id}  # a dictionary of the query variables
    cursor.execute(query, vars)                       # using Python's sqlite3 module
    

    See documentation of Cursor.execute-function.

    "This is the [most pythonic] way!" - ...

    0 讨论(0)
  • 2020-11-22 01:15

    For example:

    sql = ("select field1, field2, field3, field4 "
           "from table "
           "where condition1={} "
           "and condition2={}").format(1, 2)
    
    Output: 'select field1, field2, field3, field4 from table 
             where condition1=1 and condition2=2'
    

    if the value of condition should be a string, you can do like this:

    sql = ("select field1, field2, field3, field4 "
           "from table "
           "where condition1='{0}' "
           "and condition2='{1}'").format('2016-10-12', '2017-10-12')
    
    Output: "select field1, field2, field3, field4 from table where
             condition1='2016-10-12' and condition2='2017-10-12'"
    
    0 讨论(0)
  • 2020-11-22 01:15

    I usually use something like this:

    text = '''
        This string was typed to be a demo
        on how could we write a multi-line
        text in Python.
    '''
    

    If you want to remove annoying blank spaces in each line, you could do as follows:

    text = '\n'.join(line.lstrip() for line in text.splitlines())
    
    0 讨论(0)
提交回复
热议问题