Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 885
whytheq Avatar asked May 25 '16 08:05

whytheq


People also ask

How do you write a string in multiple lines in a Jupyter notebook?

Use a backslash ( \ ) as a line continuation character If a backslash is placed at the end of a line, it is considered that the line is continued on the next line. Only string literals (string surrounded by ' or " ) are concatenated if written consecutively. Note that in the case of variables, an error is raised.

How do I create a multiline string in Python?

Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.

What is %% capture in Jupyter?

What does %% capture do in Jupyter? Capturing Output With %%capture IPython has a cell magic, %%capture , which captures the stdout/stderr of a cell. With this magic you can discard these streams or store them in a variable. By default, %%capture discards these streams. This is a simple way to suppress unwanted output.


1 Answers

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.)

like image 139
tbayer Avatar answered Oct 23 '22 19:10

tbayer