How do you encode a multiline string in python?

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!" - ...

Python has got different ways to represent strings. A Python multiline string is the most efficient way of presenting multiple string statements in a formatted and optimized manner.

In this article, we will be focusing on the different techniques that can be used to create Python multiline strings.

Technique 1: Triple quotes to create multiline strings in Python

The triple quotes can be used to display multiple strings together i.e. multiline strings in Python.

Syntax:

variable = """ strings """

  • If our input contains string statements with too many characters, then triple quotes can serve us with the need to display it in a formatted way.
  • Everything that comes under the triple quotes is considered as the string itself.

Example:

inp_str = """You can find the entire set of tutorials for Python and R on JournalDev.
Adding to it, AskPython has got a very detailed version of Python understanding through its easy to understand articles."""
print[inp_str]

Output:

You can find the entire set of tutorials for Python and R on JournalDev.
Adding to it, AskPython has got a very detailed version of Python understanding through its easy to understand articles.

Technique 2: Using backslash [\] for multiline string creation

The escape sequence — backslash ['\'] is used to create multiline strings in Python.

Syntax:

variable = "string1"\"string2"\"stringN"

  • While creating multiline strings using backslash[\], the user needs to explicitly mention the spaces between the strings.

Example:

inp_str = "You can find the entire set of tutorials for Python and R on JournalDev."\
"Adding to it, AskPython has got a very detailed version of Python understanding through its easy to understand articles."\
"Welcome to AskPython!!"
print[inp_str]

As clearly seen below, it does not manage the spaces between the statements. The user has to mention it at the time of declaration of the multiline strings.

Output:

You can find the entire set of tutorials for Python and R on JournalDev.Adding to it, AskPython has got a very detailed version of Python understanding through its easy to understand articles.Welcome to AskPython!!

Technique 3: The string.join[] method to build a Python multiline string

Python string.join[] method has turned out to be an efficient technique to create Python multiline strings.

The string.join[] method handles and manipulates all the spaces between the strings and the user does not need to worry about the same.

Syntax:

string.join[["string1","string2","stringN"]]

Example:

inp_str =' '.join[["You can find the entire set of tutorials for Python and R on JournalDev.",
                   "Adding to it", 
                   "AskPython has got a very detailed version",
                   "of Python understanding through its easy to understand articles.",
                   "Welcome to AskPython!!"]]
print[inp_str]

Output:

You can find the entire set of tutorials for Python and R on JournalDev. Adding to it AskPython has got a very detailed version of Python understanding through its easy to understand articles. Welcome to AskPython!!

Technique 4: Python round brackets [] to create multiline strings

Python brackets can be used to create multiline strings and split the strings together.

The only drawback of this technique is that, the user needs to explicitly mention the spaces between the multiline strings.

Syntax:

variable = ["string1""string2""stringN"]

Example:

inp_str =["You can find the entire set of tutorials for Python and R on JournalDev."
                   "Adding to it "
                   "AskPython has got a very detailed version "
                   "of Python understanding through its easy to understand articles."
                   "Welcome to AskPython!!"]
print[inp_str]

Output:

You can find the entire set of tutorials for Python and R on JournalDev.Adding to it AskPython has got a very detailed version of Python understanding through its easy to understand articles.Welcome to AskPython!!

Summary

  • Python multiline strings are the strings split into multiple lines to enhance the readability of the code for the users.
  • Python brackets, backslash, and triple quotes can be used to create multiline strings but here, the user needs to mention the use of spaces between the strings.
  • Python string.join[] method is considered to be a very efficient way to build multiline strings and moreover, the spaces between the strings are implicitly handled by the method.
  • Python indentation rules are not applicable to multiline strings.
  • All the escape sequences such as newline[\n], tab-space[\t] are considered as a part of string if the multiline string is created using triple quotes.

Conclusion

Thus, in this article, we have understood the various ways of creating Python multiline strings.

References

  • Python multiline strings — JournalDev

How do you read a multiline string in Python?

Multiline String in Python:.
By using three double quotes: Python multiline string begins and ends with either three single quotes or three double-quotes. ... .
By using three single quotes: Example: ... .
Using Brackets. Using brackets we can split a string into multiple lines. ... .
Using Backslash. ... .
Multiline String creation using join[].

What are the two ways to write a multiline string?

There are three ways to create strings that span multiple lines: By using template literals. By using the + operator – the JavaScript concatenation operator. By using the \ operator – the JavaScript backslash operator and escape character.

Chủ Đề