whytheq
whytheq

Reputation: 35557

Multiline strings in Jupyter notebook

How do I split thE sql string x, in the following snippet, onto several lines - this is in a Jupyter notebook?

import pandas as pd
import pyodbc as p

def s(sqlString):
    cnxn = p.connect(driver='{SQL Server}', server='SERVERNAME', database='OURDBNAME', uid='myLOGIN', pwd='myPWD')
    df = pd.read_sql(sqlString, cnxn)
    return df


x = "SELECT * FROM OURDBNAME.dbo.vw_DimFoo"
df = s(x)

(Ideally I'd like to not have to deal with lots of concatenation ...not sure if this is possible)

Upvotes: 7

Views: 33070

Answers (2)

tbayer
tbayer

Reputation: 331

Use Python's triple quote notation to define a multi-line string:

x = """\
Select * 
FROM OURDBNAME.dbo.vw_DimFoo
"""

print(x)

results in

Select * 
FROM OURDBNAME.dbo.vw_DimFoo

(The backslash "\" at the beginning suppresses a line break. To define a single-line string using several lines, add backslashes after each line.)

Upvotes: 23

cel
cel

Reputation: 31339

Using round brackets will allow you to split your string over multiple lines. If you do not use an operator, python will simply concate.

So quick example:

x = (
  'Select * '
  'FROM OURDBNAME.dbo.vw_DimFoo '
  'WHERE <foo> '
)

print(x)

prints

Select * FROM OURDBNAME.dbo.vw_DimFoo WHERE <foo> 

Upvotes: 13

Related Questions