{"id":3487,"date":"2019-09-09T11:38:58","date_gmt":"2019-09-09T09:38:58","guid":{"rendered":"https:\/\/pythonprogramming.altervista.org\/?p=3487"},"modified":"2019-09-09T17:17:15","modified_gmt":"2019-09-09T15:17:15","slug":"transform-a-python-multiline-string-into-html-table","status":"publish","type":"post","link":"https:\/\/pythonprogramming.altervista.org\/transform-a-python-multiline-string-into-html-table\/","title":{"rendered":"Transform a Python multiline string into Html table"},"content":{"rendered":"<p>This is not the first time I make a post about transforming a <strong>multiline string<\/strong> in Python into an <strong>html<\/strong> table. This time I made the code the simplest ever&#8230; at least I tried.<\/p>\n<p>This can be used to insert a table:<\/p>\n<ul>\n<li>in your blog<\/li>\n<li>in a document made using html tags<\/li>\n<li>for any other stuff that uses html<\/li>\n<\/ul>\n<p>The reason of the code is essentially that to make even a simple table in html is very boring, but it is a very good way to insert data in an html page.<\/p>\n<h2>A basic html table tags<\/h2>\n<p>This is how the tags to make a table in html is:<\/p>\n<pre class=\"lang:default decode:true\">&lt;table border=1&gt;\r\n\r\n&lt;\/table&gt;<\/pre>\n<p>In this tags the rows go.<\/p>\n<p>Every tag for the row is like this:<\/p>\n<pre class=\"lang:default decode:true \">&lt;table border=1&gt;\r\n &lt;tr&gt;&lt;td&gt; cell1 &lt;\/td&gt;&lt;td&gt; cell2 &lt;\/td&gt;&lt;\/tr&gt; \r\n &lt;tr&gt;&lt;td&gt; cell1 &lt;\/td&gt;&lt;td&gt; cell2 &lt;\/td&gt;&lt;\/tr&gt;\r\n&lt;\/table&gt;<\/pre>\n<p>This is just a 2&#215;2 table, imagine how complex can be a table with more rows and columns.<\/p>\n<p>Furthermore, there are the &lt;th&gt; tag for the row header and the colspan attribute of &lt;td&gt; for the data that occupies more than one cell. I suggested a way to handle colspan in the second script you see in this post.<\/p>\n<h2>Simplify stuffs with Python<\/h2>\n<p>All you have to do is to insert the data in a multiline string like this.<\/p>\n<pre class=\"lang:default decode:true \">a = \"\"\"\r\nname city year\r\nJohn York 2000\"\"\"<\/pre>\n<p>I like to use multiline strings that are then converted into arrays (lists) instead of creating a list directly, because it is so easy to write and read too (and to modify it too). You can easily copy the data from an Excel file and paste it in the multiline string, as I showed in other posts, to get the job done.<\/p>\n<p>Here is how to transform the multiline string in a list of strings with each line in each item of the list:<\/p>\n<pre class=\"lang:default decode:true \">for line in x.splitlines():<\/pre>\n<p>So once you have a line in each ites, each line is divided in cells by the spaces:<\/p>\n<pre class=\"lang:default decode:true \">for n in line.split():<\/pre>\n<p>Then I cumulate the &lt;td&gt; into the html variable:<\/p>\n<pre class=\"lang:default decode:true \">html += f\"&lt;td&gt;{n}&lt;\/td&gt;\"<\/pre>\n<h2>The whole code<\/h2>\n<pre class=\"lang:default decode:true\"># How to make a table in html\r\n# ... with Python\r\nimport os\r\n\r\n\r\ndef table(x, border=1, show = 0):\r\n\t\"\"\" Create table with data in a multiline\r\n\tstring as first argument x)\"\"\"\r\n\thtml = f\"&lt;table border={border}&gt;\"\r\n\tfor line in x.splitlines():\r\n\t\tfor n in line.split():\r\n\t\t\thtml += f\"&lt;td&gt;{n}&lt;\/td&gt;\"\r\n\t\thtml += \"&lt;tr&gt;\"\r\n\thtml += \"&lt;\/table&gt;\"\r\n\tif show == 1:\r\n\t\tfilename = \"file.html\"\r\n\t\twith open(filename, \"w\") as file:\r\n\t\t\tfile.write(html)\r\n\t\tos.startfile(filename)\r\n\tprint(\"To save the file use show=1\")\r\n\tprint(html)\r\n\treturn html\r\n\r\n\r\na = \"\"\"\r\nname city year\r\nJohn York 2000\"\"\"\r\n# to save the file use arg show=1\r\ntable(a, show=1)<\/pre>\n<p>This is the output at the console:<\/p>\n<pre class=\"lang:default decode:true\">To save the file use show=1\r\n&lt;table border=1&gt;&lt;tr&gt;&lt;td&gt;name&lt;\/td&gt;&lt;td&gt;city&lt;\/td&gt;&lt;td&gt;year&lt;\/td&gt;&lt;tr&gt;&lt;td&gt;John&lt;\/td&gt;&lt;td&gt;York&lt;\/td&gt;&lt;td&gt;2000&lt;\/td&gt;&lt;tr&gt;&lt;\/table&gt;\r\n&gt;&gt;&gt;<\/pre>\n<p>This is the file html saved and showed in the browser automatically:<\/p>\n<table border=1><tr><td>name<\/td><td>city<\/td><td>year<\/td><tr><td>John<\/td><td>York<\/td><td>2000<\/td><tr><\/table>\n<h2>Adding colspan<\/h2>\n<p>In case you want to ad a title to the table that uses colspan you can use this code that checks if a line starts with &#8216;&gt;&#8217; it will show it like a &#8216;title&#8217; (i.e. with one only text without columns). This works searching through the max length of the colums in this function:<\/p>\n<pre class=\"lang:default decode:true \">def find_len(a):\r\n    l = a.splitlines()\r\n    colspan = 0\r\n    for line in l:\r\n        if len(line.split()) &gt; colspan:\r\n            colspan = len(line.split())\r\n    return colspan<\/pre>\n<p>The whole code is this (it si made in jupyter lab, that&#8217;s why there is the IPython.display import, to show in jupyter lab the html. If you use another editor, you do not need those lines of code.<\/p>\n<pre class=\"lang:default decode:true \"># How to make a table in html\r\n# ... with Python\r\nimport os\r\nfrom IPython.display import display, HTML\r\n\r\ndef find_len(a):\r\n    l = a.splitlines()\r\n    colspan = 0\r\n    for line in l:\r\n        if len(line.split()) &gt; colspan:\r\n            colspan = len(line.split())\r\n    return colspan\r\n\r\ndef table(x, border=1, show = 0):\r\n\t\"\"\" Create table with data in a multiline\r\n\tstring as first argument x)\"\"\"\r\n\thtml = f\"&lt;table border={border}&gt;\"\r\n\tfor line in x.splitlines():\r\n\t\tif line.startswith(\"&gt;\"):\r\n\t\t\tline = line.replace(\"&gt;\",\"\")\r\n\t\t\thtml += f\"&lt;td colspan={find_len(a)}&gt;&lt;center&gt;{line}&lt;\/center&gt;&lt;\/td&gt;&lt;tr&gt;\"\r\n\t\t\tcontinue\r\n\t\tfor n in line.split():\r\n\t\t\thtml += f\"&lt;td&gt;{n}&lt;\/td&gt;\"\r\n\t\thtml += \"&lt;tr&gt;\"\r\n\thtml += \"&lt;\/table&gt;\"\r\n\tif show == 1:\r\n\t\tfilename = \"file.html\"\r\n\t\twith open(filename, \"w\") as file:\r\n\t\t\tfile.write(html)\r\n\t\tos.startfile(filename)\r\n\tprint(\"To save the file use show=1\")\r\n\tprint(html)\r\n\treturn html\r\n\r\n# Use the symbol \"&gt;\" to make a colspan td\r\na = \"\"\"\r\n&gt;People\r\nname city year\r\nJohn York 2000\r\n\"\"\"\r\n# to save the file use arg show=1\r\ntab = table(a, show=1)\r\nHTML(tab)<\/pre>\n<p>The output<\/p>\n<table border=1><tr><td colspan=3><center>People<\/center><\/td><tr><td>name<\/td><td>city<\/td><td>year<\/td><tr><td>John<\/td><td>York<\/td><td>2000<\/td><tr><\/table>\n<h2>Other ways to do it<\/h2>\n<pre class=\"lang:default decode:true\">from IPython.core.interactiveshell import InteractiveShell\r\nInteractiveShell.ast_node_interactivity = \"all\"\r\nfrom IPython.display import display, HTML\r\n\r\n\r\nimport os\r\n\r\ndata = \"\"\"\r\n\r\n        Name,    Surname,    Age\r\n        John,    Smith,      18\r\n        Mary,    Luise,      24\r\n             \r\n\"\"\"\r\ndata = data.splitlines()\r\ndata = [d.strip() for d in data]\r\ndata = [f\"&lt;tr&gt;&lt;td&gt;{d}&lt;\/tr&gt;\" for d in data if d.strip() != \"\"]\r\ndata = \"&lt;table border=1&gt;\" + \"\".join(data) + \"&lt;\/table&gt;\"\r\n#display(HTML(data))\r\ndata = data.replace(\"    \",\"\")\r\ndata = data.replace(\",\",\"&lt;\/td&gt;&lt;td&gt;\")\r\ndata\r\ndisplay(HTML(data))\r\n#with open(\"table.html\", \"w\", encoding=\"utf-8\") as file:\r\n    #file.write(data)\r\n#os.startfile(\"table.html\")<\/pre>\n<table border=1><tr><td>Name<\/td><td>Surname<\/td><td>Age<\/tr><tr><td>John<\/td><td>Smith<\/td><td>  18<\/tr><tr><td>Mary<\/td><td>Luise<\/td><td>  24<\/tr><\/table>\n<h2>The speed coding of the first script<\/h2>\n<p><iframe loading=\"lazy\" title=\"Speed Coding from string to Html Table\" width=\"747\" height=\"420\" src=\"https:\/\/www.youtube.com\/embed\/eEMqr6sbiIk?feature=oembed&amp;enablejsapi=1\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p>&nbsp;<\/p>\n<h2>Give the table some style<\/h2>\n<p>In this code I added some style to make the table look better:<\/p>\n<pre class=\"lang:default decode:true \"># How to make a table in html\r\n# ... with Python\r\nimport os\r\nfrom IPython.display import display, HTML\r\n\r\ndef find_len(a):\r\n    l = a.splitlines()\r\n    colspan = 0\r\n    for line in l:\r\n        if len(line.split()) &gt; colspan:\r\n            colspan = len(line.split())\r\n    return colspan\r\n\r\ndef style():\r\n\tst1 = \"\"\"&lt;style&gt;\r\n#customers {\r\n  font-family: \"Trebuchet MS\", Arial, Helvetica, sans-serif;\r\n  border-collapse: collapse;\r\n  width: 100%;\r\n}\r\n\r\n#customers td, #customers th {\r\n  border: 1px solid #ddd;\r\n  padding: 8px;\r\n}\r\n\r\n#customers tr:nth-child(even){background-color: #f2f2f2;}\r\n\r\n#customers tr:hover {background-color: #ddd;}\r\n\r\n#customers th {\r\n  padding-top: 12px;\r\n  padding-bottom: 12px;\r\n  text-align: left;\r\n  background-color: #4CAF50;\r\n  color: white;\r\n}\r\n&lt;\/style&gt;\"\"\"\r\n\treturn st1\r\n\r\ndef table(x, border=1, show = 0):\r\n\t\"\"\" Create table with data in a multiline\r\n\tstring as first argument x)\"\"\"\r\n\thtml = style()\r\n\thtml += f\"&lt;table id='customers' border={border}&gt;\"\r\n\tfor line in x.splitlines():\r\n\t\tif line.startswith(\"&gt;\"):\r\n\t\t\tline = line.replace(\"&gt;\",\"\")\r\n\t\t\thtml += f\"&lt;th colspan={find_len(a)}&gt;&lt;center&gt;{line}&lt;\/center&gt;&lt;\/th&gt;&lt;tr&gt;\"\r\n\t\t\tcontinue\r\n\t\tfor n in line.split():\r\n\t\t\thtml += f\"&lt;td&gt;{n}&lt;\/td&gt;\"\r\n\t\thtml += \"&lt;tr&gt;\"\r\n\thtml += \"&lt;\/table&gt;\"\r\n\tif show == 1:\r\n\t\tfilename = \"file.html\"\r\n\t\twith open(filename, \"w\") as file:\r\n\t\t\tfile.write(html)\r\n\t\tos.startfile(filename)\r\n\tprint(\"To save the file use show=1\")\r\n\tprint(html)\r\n\treturn html\r\n\r\n\r\na = \"\"\"\r\n&gt;People\r\nname city year\r\nJohn York 2000\r\n\"\"\"\r\n# to save the file use arg show=1\r\ntab = table(a, show=1)\r\nHTML(tab)<\/pre>\n<p>The table, now, will look like this:<\/p>\n<style>\r\n#customers {\r\n  font-family: \"Trebuchet MS\", Arial, Helvetica, sans-serif;\r\n  border-collapse: collapse;\r\n  width: 100%;\r\n}\r\n\r\n#customers td, #customers th {\r\n  border: 1px solid #ddd;\r\n  padding: 8px;\r\n}\r\n\r\n#customers tr:nth-child(even){background-color: #f2f2f2;}\r\n\r\n#customers tr:hover {background-color: #ddd;}\r\n\r\n#customers th {\r\n  padding-top: 12px;\r\n  padding-bottom: 12px;\r\n  text-align: left;\r\n  background-color: #4CAF50;\r\n  color: white;\r\n}\r\n<\/style><table id='customers' border=1><tr><th colspan=3><center>People<\/center><\/th><tr><td>name<\/td><td>city<\/td><td>year<\/td><tr><td>John<\/td><td>York<\/td><td>2000<\/td><tr><\/table>\n<p>So, if you want to give the table a personal style, just change the multiline string inside the function style(), copying and pasting the css style that you like the most and that you can easily find on the web. I took this from<\/p>\n<p><a href=\"https:\/\/www.w3schools.com\/css\/tryit.asp?filename=trycss_table_fancy\">w3school.com<\/a><\/p>\n<p>Other styles:<\/p>\n<pre class=\"lang:default decode:true \">&lt;style&gt;\r\ntable, td, th {\r\n  border: 1px solid black;\r\n}\r\n\r\ntable {\r\n  border-collapse: collapse;\r\n  width: 100%;\r\n}\r\n\r\ntd {\r\n  height: 50px;\r\n  vertical-align: bottom;\r\n}\r\n&lt;\/style&gt;<\/pre>\n<p>&nbsp;<\/p>\n<script>\r\nvar title = \"Python to Html\";\r\n\t\tvar links = [\r\n\t\t\t[\"https:\/\/pythonprogramming.altervista.org\/make-html-tables-with-pandas\/\",\"Excel to Html Table with Pandas\"],\r\n\t\t\t\/\/ ------------------- 9.9.2019 ---------------------------------\r\n\t\t\t[\"https:\/\/pythonprogramming.altervista.org\/transform-a-python-multiline-string-into-html-table\",\r\n\t\"From Python multiline string to Html table (9 9 2019)\"],\r\n\t\t\t\r\n\t\t\t[\"https:\/\/pythonprogramming.altervista.org\/python-to-make-html-tables-code\/\",\r\n\t\t\t \"Python to make Html tables code (22 7 2019)\"],\r\n\t\t\t\r\n\t\t\t [\"https:\/\/pythonprogramming.altervista.org\/creare-una-tabella-html-con-python\/\",\r\n\t\t\t \"Create Html table with Python (24 4 2019)\"],\r\n\t\t\t\r\n\t\t\t[\"https:\/\/pythonprogramming.altervista.org\/excel-data-to-html-report-the-easy-way\/\",\r\n\t\t\t \"From Excel to Html report easy (5 8 2019)\"],\r\n\t\t\t\r\n\t\t\t[\"https:\/\/pythonprogramming.altervista.org\/1563-2\/\",\r\n\t\t\t \"Create a table, but with Python (14 11 2018)\"],\r\n\t\t\t\r\n\t\t\t[\"https:\/\/pythonprogramming.altervista.org\/creare-una-tabella-con-python\/\",\r\n\t\t\t \"Creare una tabella Html con Python (18 11 2018)\"],\r\n\t\t\t\r\n\t\t\t[\"https:\/\/pythonprogramming.altervista.org\/python-and-javascript-a-quiz-made-in-javascript\/\",\r\n\t\t\t \"A quiz made in javascript (3 9 2019)\"]\r\n\t\t];\r\n\t\t\r\n\t<\/script>\r\n<script>\r\n\t\r\nif (typeof next2 != \"undefined\"){let next2 = 0;}\r\n\t\r\nnext2 = 0;\r\n\thtml = \"\";\/\/<b style='color:coral;font-size:1.2em'>Other posts about \" + title + \"<\/b><br>\";\r\nfor (address of links) \r\n{\r\n\r\n\tif (next2 == 1){\r\n\t\thtml += \"<div style='background:coral'>\";\r\n\t\thtml += \"Next link => <a href='\" + address[0] + \"'>\" + address[1] + \"<\/a>\";\r\n\t\thtml += \"<\/div><br>\";\r\n\t\tnext2 = 0;\r\n\t}\r\n\tif (address[0] == document.URL) {\r\n\t\tnext2 = 1;\r\n\t}\r\n}\r\n\r\nif (typeof next != \"undefined\") {let next = 0;}\r\nif (typeof addressStart != \"undefined\") {let addressStart = \"\";}\r\nnext = 0;\r\naddressStart = \"<a href='\";\r\nfor (address of links) {\r\n\tif (next == 1){\r\n\t\thtml += \">>>\" + addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t\tnext = 0;\r\n\t}\r\n\telse if (addressStart + address[0] != document.URL)\r\n\t{\r\n\t\thtml += addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tnext = 1;\r\n\t\tnext_address = address[0]\r\n\t\tnext_title = address[1]\r\n\t\thtml += \"<span style='color:gray'>\" + address[1] + \"<\/span><br>\";\r\n\t}\r\n\r\n}\r\n\r\n\thtml += `<span style=\"font-size:8px\">Powered by <a href=\"https:\/\/pythonprogramming.altervista.org\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2673\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png\" alt=\"\" width=\"70\" height=\"25\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png 156w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2-150x56.png 150w\" sizes=\"auto, (max-width: 70px) 100vw, 70px\" \/>pythonprogramming.altervista.org<\/a><\/span>`\r\n\thtml = \"<div style='background:yellow'>\" + html + \"<\/div>\";\r\n\tdocument.write(html)\r\n<\/script>\n","protected":false},"excerpt":{"rendered":"This is not the first time I make a post about transforming a multiline string in Python into an html table. This time \n<a class=\"moretag\" href=\"https:\/\/pythonprogramming.altervista.org\/transform-a-python-multiline-string-into-html-table\/\"> [...]<\/a>","protected":false},"author":1,"featured_media":3490,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","footnotes":""},"categories":[542,211],"tags":[],"class_list":["post-3487","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-html-with-python","category-lists-basics"],"avopt_banners_inside_post":true,"avopt_banners_on_page":true,"av_copy_from":"","av_sharing_message":"","av_sharing_allowed":false,"av_sharing_on":{"fb":[],"tw":[]},"av_allow_affiliate_banner":false,"av_allow_affiliate_multi_banner":false,"av_show_affiliation_buy_button":false,"av_post_rating":true,"av_have_post_rating_value":false,"av_is_artificial_intelligence_content":false,"_links":{"self":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/3487","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/comments?post=3487"}],"version-history":[{"count":12,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/3487\/revisions"}],"predecessor-version":[{"id":3494,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/3487\/revisions\/3494"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/media\/3490"}],"wp:attachment":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/media?parent=3487"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/categories?post=3487"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/tags?post=3487"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}