python3字符串插值 - 两种方式,都不起作用

时间:2017-06-26 12:54:01

标签: python python-3.x

鉴于这两个不同的字符串插值节,两者都不起作用。两者都将{n}和%(text)插入返回为输出中的普通原始文本。我错过了什么?

我一直在python2中使用%(string)方法,现在移植到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"
    }
)

和:

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

2 个答案:

答案 0 :(得分:2)

format%仅适用于添加的字符串的最后一个字符串。你可以使用"""(三重引号字符串)或括号括起来(你做了,但是做错了):

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

或使用三引号/原始字符串/自动格式定位:

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

除此之外:如果您想在代码中生成文字format,则\\n的第三个参数应为\n或r \n

答案 1 :(得分:0)

这是最易读的方法:

在Python 3中,您可以使用文字字符串插值或f字符串,请参见PEP 498-请注意正确地转义反斜杠,尤其是在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}');"""