Search code examples
pythonspyder

How to read multiple lines with breaks in a Function?


I wanted to know how to read multiple lines in a function and then run it. For example I am reading this path what should I put in the end of my second line so that it reads ',sheet_name='Live Promos' and run properly.

Live_Promo=pd.read_excel("""C:\\Users\\BF68499\\_Inc\\Documents\\\
                         KT\\Pro\\92-2l D_TS.xlsx"""
                         ,sheet_name='Live Promos')
#Output
#FileNotFoundError: [Errno 2] No such file or directory:

When I keep it in single line like this it reads it fine.

Live_Promo=pd.read_excel("C:\\Users\\BF64899\\_Inc\\Documents\\KT\\Pro\\92-2l D_TS.xlsx",sheet_name='Live Promos')
#Output
#reads file fine

What is the solution?


Solution

  • From the documentation of str (emphasis mine):

    Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal.

    Example:

    In [5]: print("""C:\\Users\\BF68499\\_Inc\\Documents\\\
       ...:                          KT\\Pro\\92-2l D_TS.xlsx""")
    C:\Users\BF68499\_Inc\Documents\                         KT\Pro\92-2l D_TS.xlsx
    

    This is probably not what you intended...

    You can use a backslack between strings on multiple lines. That will lead to the strings being combined:

    In [3]: print("foo"\
       ...: "bar")
    foobar
    

    Alternatively, you can put multiple strings in an expression with only whitespace between them:

    In [4]: print(("spam " "eggs"))
    spam eggs
    

    You can also use a string join:

    long_list = [
        "string1",
        "string2",
        "string3",
        "string4",
        "string5",
    ]
    really_long_string = ''.join(long_list)