簡體   English   中英

如何進行不帶引號的 Python 字符串格式化?

[英]How to do Python string formatting without quotes?

我正在寫一個 Python function 為 SQL 查詢做字符串格式化。 因此,字符串格式需要非常精確。

目前,我有一個 SQL 查詢模板字符串,我正在嘗試使用str.format()填寫值。

想象一下這樣的事情:

sql_query_template.format(arg1=arg1, arg2=arg2)

我遇到的一個問題是 Python 字符串的引號位置。

期望的結果:

(ARRAY[‘blah’, ‘25’], ‘test_group_1’, '243'),(ARRAY[‘blah2’, '12'], ‘test_group_2', '21')
  • 目標是在使用ARRAY[]關鍵字時創建元組,重要的是ARRAY[]不要變成'ARRAY[]'或整個元組被引號包圍 -> SQL 需要將關鍵字視為關鍵字。

當前結果:

(‘ARRAY[blah, 25]’, ‘test_group_1’, '243'),(‘ARRAY[blah2, 12]’, ‘test_group_2', '21')
  • 這里ARRAY[]被引號括起來(例如: 'ARRAY[blah, 25]'
  • 這是有問題的,因為 Presto 不會將ARRAY識別為關鍵字並將'ARRAY[]'視為字符串

當前片段:

# dummy example:
test_dict = json.loads(
    json.dumps(
        [
            {
                "parameter_1": ["blah", "25"],
                "parameter_2": "test_group_1",
                "parameter_3": "243",
            },
            {
                "parameter_1": ["blah2", "12"],
                "parameter_2": "test_group_2",
                "parameter_3": "21",
            },
        ]
    )
)

list_of_tuples = []
for dict in test_dict:
    list_of_tuples.append(
        (
            "ARRAY[{}]".format(",".join(dict[“parameter_1"])),
            dict["parameter_2"],
            f"{dict[parameter_3]}",
        )
    )
formatted_tuples = ",".join(
    str(tup) for tup in list_of_tuples
)
print(sql_query_template.format(arg1=formatted_tuples))

是否有可能以這樣一種方式編寫 Python 代碼,其中字符串格式將插入未包含在引號中的某些部分?

關鍵部分似乎是: "ARRAY[{}]".format(",".join(dict[“parameter_1"])),這非常接近但不是您似乎需要的。

問題是

"ARRAY[{}]".format(param)

您必須用'進行修改,以便獲得所需的報價:

"ARRAY['{}']".format(param)

你可以使用 MWE 檢查這個作品:

param = 44
print("ARRAY['{}']".format(param))

給出 output:

ARRAY['12']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM