Reputation:
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?
Upvotes: 0
Views: 93
Reputation: 56527
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.
Upvotes: 1
Reputation: 702
by having the strings in a list and then doing a join as in ' '.join(list)
. This will be a lot faster than simple concatenation.
list = ["The quick brown", "fox"]
result = " ".join(list)
Here is a link to see the difference is performance
Upvotes: 0
Reputation: 880399
You could use a multiline string:
args = (settings["app.name"], ncc, name, settings["dir"]["static.style"],
settings["lang.style"], settings["dir"]["static.script"],
settings["lang.script"])
content = """\
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>{0} - {1}</title>
<link rel="stylesheet" type="text/css" href="{3}/{2}.{4}" />
</head>
<body>
<!-- layout... -->
<script type"text/javascript" src="{5}/{2}.{6}"></script>
</body>
</html>""".format(args)
Upvotes: 0