简体   繁体   English

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

[英]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. 两者都在输出中返回{n}和%(text)插入为纯原始文本。 What am I missing? 我想念什么?

Ive been using the %(string)s method forever in python2, now porting to python 3. 我一直在python2中永远使用%(string)s方法,现在移植到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")
)

either format or % apply only to the last string of your added strings. format%仅适用于所添加字符串中的最后一个字符串。 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. 另外:如果要在代码中生成文字\\n ,则format的第三个参数应为\\\\n或r \\n

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} 在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}');"""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM