Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

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 + operator (I know, maybe it's not the most efficient way to do it, but I'm not really concerned about performance in this stage, just code readability). Example:

var long_string = 'some text not important. just garbage to' + 'illustrate my example';

I tried doing something similar in Python, but it didn't work, so I used \ to split the long string. However, I'm not sure if this is the only/best/pythonicest way of doing it. It looks awkward. Actual code:

query = 'SELECT action.descr as "action", '\

' as role_id,'\ 

'role.descr as role'\ 

'FROM '\ 



'public.record_def, '\ 


'WHERE = role_action_def.role_id AND'\ 

' = role_action_def.def_id AND'\

' = 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

1 Answer

0 votes
by (106k points)
edited by

Multi-line strings can be done easily, with the use of triple quotes to start and end them.

Following is the example that tells us how to use multi-line code:-

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 the start and end) and treat the resulting string just like any other string.

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers

Browse Categories