Home >Backend Development >Python Tutorial >How Do I Split Long Strings Across Multiple Lines in Python?
When working with lengthy queries or other long strings, it can be challenging to keep code readable. In JavaScript, you can concatenate multiple sentences using the operator to split the string across lines. However, this approach may not yield the desired results in Python.
Instead, Python offers two alternatives for splitting long strings:
This is the preferred and most Pythonic method. To create a multi-line string, use three single or double quotes at the beginning and end of the string. Anything between the quotes will become part of the string, including blanks and newlines.
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
Another option is to use parenthesis, similar to the operator in JavaScript. However, no commas are necessary. Simply place the strings to be joined into a pair of parenthesis.
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 )
Note that this approach will not include any extra blanks or newlines. Be sure to account for any necessary spacing and line breaks manually.
The above is the detailed content of How Do I Split Long Strings Across Multiple Lines in Python?. For more information, please follow other related articles on the PHP Chinese website!