三重引号内的Python参数

时间:2015-03-29 23:56:15

标签: python mysql string string-interpolation

我有一个包含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
""")

4 个答案:

答案 0 :(得分:4)

您可以像这样使用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'

答案 1 :(得分:2)

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

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

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

答案 2 :(得分:0)

我很惊讶,没有提到神话般的%运算符,以字符串格式构建的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 ))

答案 3 :(得分:0)

我将通过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))