在处理一些 SQL 格式化时,我惊讶地发现我可以链接字符串格式化程序:
def get_sql(table, limit=True):
sql = "select report_date from %s"
if limit:
result = "%s limit 1" % sql % table
else:
result = sql % table
return result
这是合法的吗?有什么理由不这样做吗?
最佳答案
它之所以有效是有道理的,因为像这样的语句:
'some value goes here %s' % value
实际上返回一个字符串。这样看可能更合乎逻辑:
result = ("%s limit 1"% sql) % table
这样做并没有明显的错误,但是链接运算符可能会导致无法确定错误的来源。
例如,这工作正常:
>>> sql = 'a value of %s'
>>> x = 'some string %s with stuff'
>>> y = 'VALUE'
>>> x % sql % y
'some string a value of VALUE with stuff'
但是如果那里有格式错误(我意识到这个例子是病态的,但它明白了要点):
>>> sql = 'a value of %d'
>>> x = 'some string %d with stuff'
>>> y = 123
>>> x % sql % y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str
确实不清楚是哪个 %d
导致了您的错误。出于这个原因,我会把它分开,如果可能的话,每行只使用一个 %
格式化程序,因为这样回溯将能够准确地指出哪一行和哪个格式化程序有问题。
郑重声明,通过每行一个格式化程序,对于其他必须阅读您的代码并试图弄清楚发生了什么的人来说,您的生活也会变得更加轻松。
关于python - Python 中的链式字符串格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3268825/