Omortis
Omortis

Reputation: 1530

python3 string interpolation - two ways, neither one works

Given these 2 different string interpolation stanzas, neither one works. Both return the {n} and %(text) inserts as plain, raw text in the output. What am I missing?

Ive been using the %(string)s method forever in python2, now porting to python 3.

bulk_string = (
    "bulk insert SomeDB.dbo.%(lru)s\n" +
    "from 'C:\\Someplace\\"
    "project\\%(filename)s'\n" +
    "with (\n" +
    "  FIELDTERMINATOR = ',',\n" +
    "  ROWTERMINATOR = '%(term)s'\n" +
    ");"
    % {
        'lru': lru,
        'filename': filename,
        'term' : "\n"
    }
)

and:

bulk_string = (
    "bulk insert SomeDB.dbo.{0}\n" +
    "from 'C:\\Someplace\\"
    "project\\{1}'\n" +
    "with (\n" +
    "  FIELDTERMINATOR = ',',\n" +
    "  ROWTERMINATOR = '{2}'\n" +
    ");"
    .format(lru, filename, "\n")
)

Upvotes: 2

Views: 1427

Answers (2)

Hendrik F
Hendrik F

Reputation: 3930

Here is the most readable way to do this:

In Python 3, you can use literal string interpolation, or f-strings, see PEP 498 - just be careful with escaping the backslashes properly, especially in front of a curly bracket such as in C:\Someplace\project\\{filename}

lru = "myTable"
filename = "myFile"
rt = "\\n"
bulk_string = f"""bulk insert SomeDB.dbo.{lru} 
                  from 'C:\Someplace\project\\{filename}'
                  with ( FIELDTERMINATOR = ,
                         ROWTERMINATOR = '{rt}');"""

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140276

either format or % apply only to the last string of your added strings. You could use """ (triple quoted strings) or parenthesize the strings (that, you did, but incorrectly):

bulk_string = (
    "bulk insert SomeDB.dbo.{0}\n" +
    "from 'C:\\Someplace\\"
    "project\\{1}'\n" +
    "with (\n" +
    "  FIELDTERMINATOR = ',',\n" +
    "  ROWTERMINATOR = '{2}'\n" +
    ");")
    .format(lru, filename, "\\n")

or with triple quotes/raw string/automatic format positionning:

bulk_string = r"""bulk insert SomeDB.dbo.{}
from 'C:\Someplace\project\{}'
with (
   FIELDTERMINATOR = ',',
   ROWTERMINATOR = '{}'
   );""".format(lru, filename, "\\n")

Aside: the third parameter of format should be \\n or r\n if you want to generate a literal \n in your code.

Upvotes: 3

Related Questions