How to colour python code in HTML?

The easiest way to highlight your python code insertion into HTML is to use the following libraries: highlight.min.js, python.min.js and use script hljs.initHighlightingOnLoad(). Also you need to import proper CSS: default.min.css. It is better to load them from the given destination:


<!DOCTYPE html>
<html>
<head>
  <title>Python Code Highlighting Example</title>
  <link rel="stylesheet" href=
"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.2/styles/default.min.css">
  <script src=
"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.2/highlight.min.js">
</script>
  <script src=
"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.7.2/languages/python.min.js">
</script>
  <script>hljs.initHighlightingOnLoad();</script>
</head>
<body>
  <pre><code class="python">
    def hello_world():
        print("Hello, world!")
  </code></pre>
</body>
</html>

Python script should be included into a special code brackets:


<pre><code class="python">
 # Your code is here 
</code></pre>

That it!


Published: 2023-05-04 23:37:44
Updated: 2023-05-04 23:46:50