Reputation: 1687
I have a markdown table syntax string, say:
table_md=\
"| Tables | Are | Cool |\n\
| ------------- |-------------| -----|\n\
| col 3 is | right-aligned | $1600 |\n\
| col 2 is | centered | $12 |\n\
| zebra stripes | are neat | $1 |\n"
I would like to convert it to html syntax table string:
<table>
<thead>
<tr>
<th>Tables</th>
<th>Are</th>
<th>Cool</th>
</tr>
</thead>
<tbody>
<tr>
<td>col 3 is</td>
<td>right-aligned</td>
<td>$1600</td>
</tr>
<tr>
<td>col 2 is</td>
<td>centered</td>
<td>$12</td>
</tr>
<tr>
<td>zebra stripes</td>
<td>are neat</td>
<td>$1</td>
</tr>
</tbody>
</table>
First searching through stackoverflow, I have tried using this:
import markdown
table_html=markdown.markdown(table_md)
But the result is a html paragraph:
'<p>| Tables... |</p>'
By gooling the issue, I have come to markdown extensions, and try add the extension to the command above:
table_html=markdown.markdown(table_md, extensions=[MyExtension(), \
'markdown.extensions.tables'])
Then it shows error saying that "NameError: name 'MyExtension' is not defined"
And there is no same situation in stackoverflow.
Please help me what to do with MyExtension above. Thank you!
Upvotes: 13
Views: 11022
Reputation: 4441
firstly you can have your input like below:
table_md="| Tables | Are | Cool |\n\
| ------------- |-------------| -----|\n\
| col 3 is | right-aligned | $1600 |\n\
| col 2 is | centered | $12 |\n\
| zebra stripes | are neat | $1 |\n"
use an extension markdown.extensions.tables
table_html=markdown.markdown(table_md, extensions=['markdown.extensions.tables'])
Output is:
>>> print table_html
<table>
<thead>
<tr>
<th>Tables</th>
<th>Are</th>
<th>Cool</th>
</tr>
</thead>
<tbody>
<tr>
<td>col 3 is</td>
<td>right-aligned</td>
<td>$1600</td>
</tr>
<tr>
<td>col 2 is</td>
<td>centered</td>
<td>$12</td>
</tr>
<tr>
<td>zebra stripes</td>
<td>are neat</td>
<td>$1</td>
</tr>
</tbody>
</table>
Upvotes: 15
Reputation: 1687
I found the solution, the extension library state that "The list of extensions may contain instances of extensions and/or strings of extension names", so MyExtension() is optional, so I can delete it in this case, the solution is:
table_html=markdown.markdown(table_md, extensions=['markdown.extensions.tables'])
For those who want to adding their own additions or changes to the syntax of Markdown, you can use MyExtension as follow:
from markdown.extensions import Extension
class MyExtension(Extension):
# define your extension here...
markdown.markdown(text, extensions=[MyExtension(option='value')])
Upvotes: 4