Pythonic way to create a long multi-line string

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

提交回复
热议问题