I\'m trying to find the best way to format an sql query string. When I\'m debugging my application I\'d like to log to file all the sql query strings, and it is important t
You can use inspect.cleandoc to nicely format your printed SQL statement.
This works very well with your option 2.
Note: the print("-"*40) is only to demonstrate the superflous blank lines if you do not use cleandoc.
from inspect import cleandoc
def query():
sql = """
select field1, field2, field3, field4
from table
where condition1=1
and condition2=2
"""
print("-"*40)
print(sql)
print("-"*40)
print(cleandoc(sql))
print("-"*40)
query()
Output:
----------------------------------------
select field1, field2, field3, field4
from table
where condition1=1
and condition2=2
----------------------------------------
select field1, field2, field3, field4
from table
where condition1=1
and condition2=2
----------------------------------------
From the docs:
inspect.cleandoc(doc)
Clean up indentation from docstrings that are indented to line up with blocks of code.
All leading whitespace is removed from the first line. Any leading whitespace that can be uniformly removed from the second line onwards is removed. Empty lines at the beginning and end are subsequently removed. Also, all tabs are expanded to spaces.