与三元运算符连接字符串

时间:2015-12-03 15:25:52

标签: python python-2.7

如果存在创建表的文件,我正在尝试动态地向查询添加一些其他字符串。如果我删除第一个三端,则结束三元组。尝试打印下面的字符串时出现语法错误。

testQuery = """
select 
fish,
"""+("""Room,""" if os.path.isfile(schoolFile)==True else """""")+
"""period_01,
period_02

from over_cs_doe d
"""+("""LEFT JOIN schools s ON s.fish=d.fish""" if os.path.isfile(schoolFile)==True else """""")

4 个答案:

答案 0 :(得分:1)

您的代码几乎没问题,问题是如果您假装在下一行中继续发表声明,则必须在行末使用\

testQuery = """
select 
fish,
"""+("""Room,""" if os.path.isfile(schoolFile) else """""") + \ #Use backslash to continue your statement
"""period_01,
period_02

from over_cs_doe d
"""+("""LEFT JOIN schools s ON s.fish=d.fish""" if os.path.isfile(schoolFile) else """""")

正如我在评论中所说,不要测试布尔值是否为真

答案 1 :(得分:0)

您可以通过这种方式混合字符串和代码,但这并不容易阅读。 为什么不尝试类似的东西:

if os.path.isfile(schoolFile):
   testQuery = """
   select Fish,Room,period_01 ...
   from ...
"""

else:
   testQuery = """
   select Fish,period_01 ...
   from ...
"""

答案 2 :(得分:0)

对于它的价值,一个更易读,更不易出错的替代方案是使用字符串插值而不是连接。

另外,正如评论所暗示的那样,'某种东西='真'以“布尔”方式肯定不被认为是好风格。这同样适用于不需要它们的三引号字符串。

因此,您的testQuery也可能如下所示:

testQuery = """
select
fish,
%s
period_01,
period_02

from over_cs_doe d
%s
""" % ("Room," if os.path.isfile(schoolFile) else "",
       "LEFT JOIN schools s ON s.fish=d.fish" if os.path.isfile(schoolFile) else "")

答案 3 :(得分:0)

对于 Python 3.6 以后的版本,我将使用 f 字符串,无需担心行延续或位置插值,例如 %s 占位符。

例如:

is_school_file = os.path.isfile(schoolFile)
testQuery = f"""
select 
  fish,
{"  room," if is_school_file else ""}
  period_01,
  period_02
from over_cs_doe as d
{"left join schools as s ON s.fish=d.fish" if is_school_file else ""}"""

如果您使用的是 DB-API 兼容的数据库库,或者像 SQLAlchemy 这样的 ORM,那么有更安全的方法来构建避免 SQL 注入的查询。这看起来不像是可能存在任何未经处理的用户输入的情况,但有责任在人们连接字符串以创建 SQL 语句的任何地方提及它,因为 SQL 注入仍然是 #1 代码漏洞。

相关问题