Search code examples
pythonpython-3.xconcatenationreadabilitycode-readability

What is the most efficient and readable way to pass/format lots of variables to a large string?


I have a couple "lengthy" lines like this one:

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"])

Just by looking at such a line it you can tell that it is quite large and that it is in some ways hard to read and / or understand.

Is there a more efficient and readable way to dynamically insert lots of values into large strings?


Solution

  • Another option would be to do:

    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"]
    )
    

    Note that there is no , at the end of each line.

    However the best way to generate HTML is probably via some templating framework, e.g. jinja, mako, etc.