Often, I’ll have to set a multi-line string in Python, such as a long SQL statement or friendly message of some sort. It would be easy to write one, long string but that wouldn’t be very readable or maintainable–having to scroll horizontally to read the string–nor would it be compliant with PEP8. So, what is a coder to do? Well, fortunately, Python has a number of ways to skin this cat:
Option 1: Concatenate your strings with plus signs
Here, I just concatenate my individual lines together with the good ol’ plus sign:
1
2
3
4 qry1 = ('SELECT fname ' +
',lname ' +
',job_title ' +
'FROM people')
Option 2: Concatenate your strings without the plus signs
Well, it turns out you don’t need the plus signs after all to concatenate your lines together:
1
2
3
4 qry2 = ('SELECT fname '
',lname '
',job_title '
'FROM people')
Option 3: Use backslashes for line concatenation
Here, you don’t need to surround your strings with parentheses…just use the backslash to do the concatenation work:
1
2
3
4 qry3 = 'SELECT fname ' \
',lname ' \
',job_title ' \
'FROM people'
Option 4: (my personal favorite) Surround your multi-line string with three double-quotes
This technique makes it very easy to read the content of your multi-line string:
1
2
3
4
5
6 qry4 = """
SELECT fname
,lname
,job_title
FROM people
"""
Bonus Option (Jupyter Notebook only): Use the sql_magic keyword
If you have a long SQL statement and are working in Jupyter Notebook, consider using the sql_magic keyword from Pivotal:
1
2
3
4
5 %%read_sql df_result -c conn
SELECT fname
,lname
,job_title
FROM people
Check out these examples in action on my Jupyter Notebook.
Recent Comments