Python 三引号内的参数

Python arguments inside triple quotes

我有一个包含 sql 查询的 python 脚本。为了格式化目的,我在 sql 查询周围使用了三重引号。我想将从命令行填充的变量注入到查询中。我怎样才能在保留三重引号的同时做到这一点。有没有更好的方法来绕过三重引号?

例如:

AGE = raw_input("Enter your age: ")

vdf = vertica.select_dataframe("""
    Select
        col1
        col2
        coln
    FROM
        TableX
    WHERE
        col2 IN (21, 22, AGE)
    Group BY 1
""")

您可以将查询字符串分开并使用格式来输入正确的年龄,例如:

a_query = """
    Select
        col1
        col2
        coln
    FROM
        TableX
    WHERE
        col2 IN (21, 22, {})
    Group BY 1
"""

vdf = vertica.select_dataframe(a_query.format(AGE))

您可以这样使用 format

AGE = raw_input("Enter your age: ")
query_1 = """
    Select
        col1
        col2
        coln
    FROM
        TableX
    WHERE
        col2 IN (21, 22, {})
    Group BY 1
"""
vdf = vertica.select_dataframe(query_1.format(AGE))

一个带有三重引号和多重赋值的简单示例是:

>>> age = 100
>>> name = "koukouviou"
>>> """I am {} and I am {} years old""".format(name, age)
'I am koukouviou and I am 100 years old'

我很惊讶,没有提到神奇的 % 运算符,pythons 内置的字符串格式将使您的原始行稍作修改即可工作:

AGE = raw_input("Enter your age: ")

vdf = vertica.select_dataframe("""
    Select
        col1,
        col2,
        coln
    FROM
        TableX
    WHERE
        col2 IN (21, 22, %s)
    Group BY 1
""" % AGE)

这也适用于具有多个参数的查询:

AGE = raw_input("Enter your age: ")
GENDER = raw_input("Enter your gender (m/f): ")
HEIGHT = raw_input("Enter your height in cm: ")

vdf = vertica.select_dataframe("""
    INSERT INTO stats (
        age,
        gender,
        height
    )
    VALUES
    (
        '%s',
        '%s',
        '%s'
    )
""" % ( AGE, GENDER, HEIGHT ))

我将通过 dict 拆包再添加一个答案,因为它让我的生活变得更加简单。使用@hexerei-software的INSERT示例:

AGE = raw_input("Enter your age: ")
GENDER = raw_input("Enter your gender (m/f): ")
HEIGHT = raw_input("Enter your height in cm: ")

settings = {'AGE': AGE, 'GENDER': GENDER, 'HEIGHT': HEIGHT}

vdf = vertica.select_dataframe("""
    INSERT INTO stats (
        age,
        gender,
        height
    )
    VALUES
    (
        '{AGE}',
        '{GENDER}',
        '{HEIGHT}'
    )
""".format(**settings))

我更喜欢使用 f-Strings!

vdf = vertica.select_dataframe(f"""
    Select
        col1
        col2
        coln
    FROM
        TableX
    WHERE
        col2 IN (21, 22, {AGE})
    Group BY 1
""")