Transform a Python multiline string into Html table

This is not the first time I make a post about transforming a multiline string in Python into an html table. This time I made the code the simplest ever… at least I tried.

This can be used to insert a table:

  • in your blog
  • in a document made using html tags
  • for any other stuff that uses html

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.

A basic html table tags

This is how the tags to make a table in html is:

<table border=1>

</table>

In this tags the rows go.

Every tag for the row is like this:

<table border=1>
 <tr><td> cell1 </td><td> cell2 </td></tr> 
 <tr><td> cell1 </td><td> cell2 </td></tr>
</table>

This is just a 2×2 table, imagine how complex can be a table with more rows and columns.

Furthermore, there are the <th> tag for the row header and the colspan attribute of <td> 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.

Simplify stuffs with Python

All you have to do is to insert the data in a multiline string like this.

a = """
name city year
John York 2000"""

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.

Here is how to transform the multiline string in a list of strings with each line in each item of the list:

for line in x.splitlines():

So once you have a line in each ites, each line is divided in cells by the spaces:

for n in line.split():

Then I cumulate the <td> into the html variable:

html += f"<td>{n}</td>"

The whole code

# How to make a table in html
# ... with Python
import os


def table(x, border=1, show = 0):
	""" Create table with data in a multiline
	string as first argument x)"""
	html = f"<table border={border}>"
	for line in x.splitlines():
		for n in line.split():
			html += f"<td>{n}</td>"
		html += "<tr>"
	html += "</table>"
	if show == 1:
		filename = "file.html"
		with open(filename, "w") as file:
			file.write(html)
		os.startfile(filename)
	print("To save the file use show=1")
	print(html)
	return html


a = """
name city year
John York 2000"""
# to save the file use arg show=1
table(a, show=1)

This is the output at the console:

To save the file use show=1
<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>
>>>

This is the file html saved and showed in the browser automatically:

namecityyear
JohnYork2000

Adding colspan

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 ‘>’ it will show it like a ‘title’ (i.e. with one only text without columns). This works searching through the max length of the colums in this function:

def find_len(a):
    l = a.splitlines()
    colspan = 0
    for line in l:
        if len(line.split()) > colspan:
            colspan = len(line.split())
    return colspan

The whole code is this (it si made in jupyter lab, that’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.

# How to make a table in html
# ... with Python
import os
from IPython.display import display, HTML

def find_len(a):
    l = a.splitlines()
    colspan = 0
    for line in l:
        if len(line.split()) > colspan:
            colspan = len(line.split())
    return colspan

def table(x, border=1, show = 0):
	""" Create table with data in a multiline
	string as first argument x)"""
	html = f"<table border={border}>"
	for line in x.splitlines():
		if line.startswith(">"):
			line = line.replace(">","")
			html += f"<td colspan={find_len(a)}><center>{line}</center></td><tr>"
			continue
		for n in line.split():
			html += f"<td>{n}</td>"
		html += "<tr>"
	html += "</table>"
	if show == 1:
		filename = "file.html"
		with open(filename, "w") as file:
			file.write(html)
		os.startfile(filename)
	print("To save the file use show=1")
	print(html)
	return html

# Use the symbol ">" to make a colspan td
a = """
>People
name city year
John York 2000
"""
# to save the file use arg show=1
tab = table(a, show=1)
HTML(tab)

The output

People
namecityyear
JohnYork2000

Other ways to do it

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
from IPython.display import display, HTML


import os

data = """

        Name,    Surname,    Age
        John,    Smith,      18
        Mary,    Luise,      24
             
"""
data = data.splitlines()
data = [d.strip() for d in data]
data = [f"<tr><td>{d}</tr>" for d in data if d.strip() != ""]
data = "<table border=1>" + "".join(data) + "</table>"
#display(HTML(data))
data = data.replace("    ","")
data = data.replace(",","</td><td>")
data
display(HTML(data))
#with open("table.html", "w", encoding="utf-8") as file:
    #file.write(data)
#os.startfile("table.html")
NameSurnameAge
JohnSmith 18
MaryLuise 24

The speed coding of the first script

 

Give the table some style

In this code I added some style to make the table look better:

# How to make a table in html
# ... with Python
import os
from IPython.display import display, HTML

def find_len(a):
    l = a.splitlines()
    colspan = 0
    for line in l:
        if len(line.split()) > colspan:
            colspan = len(line.split())
    return colspan

def style():
	st1 = """<style>
#customers {
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

#customers td, #customers th {
  border: 1px solid #ddd;
  padding: 8px;
}

#customers tr:nth-child(even){background-color: #f2f2f2;}

#customers tr:hover {background-color: #ddd;}

#customers th {
  padding-top: 12px;
  padding-bottom: 12px;
  text-align: left;
  background-color: #4CAF50;
  color: white;
}
</style>"""
	return st1

def table(x, border=1, show = 0):
	""" Create table with data in a multiline
	string as first argument x)"""
	html = style()
	html += f"<table id='customers' border={border}>"
	for line in x.splitlines():
		if line.startswith(">"):
			line = line.replace(">","")
			html += f"<th colspan={find_len(a)}><center>{line}</center></th><tr>"
			continue
		for n in line.split():
			html += f"<td>{n}</td>"
		html += "<tr>"
	html += "</table>"
	if show == 1:
		filename = "file.html"
		with open(filename, "w") as file:
			file.write(html)
		os.startfile(filename)
	print("To save the file use show=1")
	print(html)
	return html


a = """
>People
name city year
John York 2000
"""
# to save the file use arg show=1
tab = table(a, show=1)
HTML(tab)

The table, now, will look like this:

People
namecityyear
JohnYork2000

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

w3school.com

Other styles:

<style>
table, td, th {
  border: 1px solid black;
}

table {
  border-collapse: collapse;
  width: 100%;
}

td {
  height: 50px;
  vertical-align: bottom;
}
</style>

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.