Search code examples
pythonsqlsqlitef-string

f-string for multiple SQL lines


This one works (one line only):

   c.execute(f"SELECT Firm, Platform, `Sale in million` FROM database WHERE Platform IN  ({','.join('?' for _ in list_table)}) ORDER BY Firm", (list_table))

But these ones don't (2 lines):

c.execute(f"SELECT Firm, Platform, `Sale in million` FROM database 
          WHERE Platform IN  ({','.join('?' for _ in list_table)}) ORDER BY Firm", (list_table))

c.execute(f"SELECT Firm, Platform, `Sale in million` FROM database" 
          f"WHERE Platform IN  ({','.join('?' for _ in list_table)}) ORDER BY Firm", (list_table))"

c.execute("SELECT Firm, Platform, `Sale in million` FROM database" 
          f"WHERE Platform IN  ({','.join('?' for _ in list_table)}) ORDER BY Firm", (list_table))"

How do you use f-string in multiple lines?


Solution

  • The issue stems from essentially invalid multi lines and not really any fault of f-string.. Note that you only need to use your variables inside the {} parenthesis and not pass them separately with f-string syntax. Use triple quotes or backslashes at end of strings to use multi line strings. Link to docs

    test = "this is a 
           bad multiline " #Raises SyntaxError: EOL while scanning string literal
    
    test = ''' this is a 
             valid multiline'''
    
    a = "answer"
    
    print(f'''test
            is complete. check {a} ''')