将大量变量传递/格式化为大字符串的最有效和可读方法是什么?

时间:2016-06-07 17:35:46

标签: python python-3.x concat readability code-readability

我有一对"冗长的"像这样的行:

content = "<!DOCTYPE html>\n<html>\n<head>\n  <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n  <title>{0} - {1}</title>\n  <link rel=\"stylesheet\" type=\"text/css\" href=\"{3}/{2}.{4}\" />\n</head>\n<body>\n  <!-- layout... -->\n  <script type\"text/javascript\" src=\"{5}/{2}.{6}\"></script>\n</body>\n</html>\n".format(settings["app.name"], ncc, name, settings["dir"]["static.style"], settings["lang.style"], settings["dir"]["static.script"], settings["lang.script"])

只要看一下这样一条线就可以看出它很大,而且在某些方面很难阅读和/或理解。

是否有更有效和可读的方法将大量值动态插入大字符串?

3 个答案:

答案 0 :(得分:1)

另一种选择是:

    SELECT b1.gvkey, b1.iid, b1.datecol, b1.prccd, 
        b2.datecol as '35days', (b2.prccd - b1.prccd)/b1.prccd
    FROM stocks_prices b1
        LEFT JOIN stocks_prices b2
            ON b1.datecol = DATE_ADD(b2.datecol, INTERVAL 35 DAY) 
            AND b1.gvkey = b2.gvkey
            AND b1.iid = b2.iid
    WHERE b1.datecol in ('2015-01-02', '2015-02-02', '2015-03-02',  '2015-04-01',  '2015-05-01',  '2015-06-01',  '2015-07-01',  '2015-08-03',  '2015-09-01',
      '2015-10-01',  '2015-11-02',  '2015-12-01')

请注意,每行末尾没有content = ( "<!DOCTYPE html>\n<html>\n<head>\n " "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n" " <title>{0} - {1}</title>\n " "<link rel=\"stylesheet\" type=\"text/css\" href=\"{3}/{2}.{4}\" />\n</head>\n<body>\n" " <!-- layout... -->\n " "<script type\"text/javascript\" src=\"{5}/{2}.{6}\"></script>\n</body>\n</html>\n" ).format( settings["app.name"], ncc, name, settings["dir"]["static.style"], settings["lang.style"], settings["dir"]["static.script"], settings["lang.script"] )

然而,生成HTML的最佳方式可能是通过一些模板框架,例如: jinja,mako等。

答案 1 :(得分:0)

将字符串放在列表中,然后像' '.join(list)一样进行连接。这将比简单连接快得多。

list = ["The quick brown", "fox"] result = " ".join(list) 这是一个link,看看性能差异

答案 2 :(得分:0)

您可以使用multiline string

CREATE TRIGGER Trigger2c
  AFTER INSERT OR UPDATE OR DELETE
  ON SalesOrderDetail2c
  FOR EACH ROW
  EXECUTE PROCEDURE FunctionTrigger2c();