0

My python code:

#!/usr/bin/python
from markdown import markdown

fish='salmon'
print fish

s = """
| Type  | Value |
| ------------- | -------------|
| Fish   |  {{fish}} |
"""
html = markdown(s, extensions=['tables'])
print(html)

However fish in the table is not replaced with salmon. I tried quotes, single curlies, etc.

Some discussions seem to imply I need to install some more extensions, which I tried randomly.

I guess I am lacking a clean way to resolve this with steps.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
alexsuv
  • 35
  • 8

1 Answers1

1

You can just use f-strings as so:

hello = "Hey"
world = "Earth"

test = f"""{hello} {world}"""

print(test)

outputs:

Hey Earth

Simply add a f before your string, and use curly brackets ({python-code}) to insert Python code into the string (in the example above, two variables named hello and world, respectively).


Using your code as an example:

from markdown import markdown

fish = "salmon"

s = f"""
| Type  | Value |
| ------------- | -------------|
| Fish   |  {fish} |
"""
html = markdown(s, extensions=["tables"])
print(html)

Outputs:

<table>
<thead>
<tr>
<th>Type</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fish</td>
<td>salmon</td>
</tr>
</tbody>
</table>

If you are using Python 2.7, you may use the str.format() function:

from markdown import markdown

fish = "salmon"

s = """
| Type  | Value |
| ------------- | -------------|
| Fish   |  {} |
""".format(fish)

html = markdown(s, extensions=["tables"])
print(html)
felipe
  • 7,324
  • 2
  • 28
  • 37
  • I need to use markdown module to create a table and populate the table with the variables. So I guess this is more like a markdown question. – alexsuv Jan 26 '20 at 00:37
  • 1
    I think you missed the point of the answer. You may use `f-strings` for your need -- the `{{fish}}` tag you can change it to `{fish}` if you add a `f` to the beginning of the string (`f""" ... text ... """`), and your problem should be taken care of. – felipe Jan 26 '20 at 00:45
  • Your code works, per se. However I need to create a table using the **markdown** module. Sorry if I am still missing the point. – alexsuv Jan 26 '20 at 00:57
  • 1
    Edited my answer so you can see how it would work with the `markdown` module. The `markdown` module does not specify any manner for which you can pass variables to fill your strings within their [docs](https://python-markdown.github.io/reference/#the-basics) -- that is something you likely have to do pre-`markdown` use. – felipe Jan 26 '20 at 01:02
  • I see you pasted the code with the markdown, thank you. It does not work for me, probably because my python version is old (2.7). I am on imac and it comes with the default v2.7. Thank you again! – alexsuv Jan 26 '20 at 01:03
  • Added compatibility for Python 2.7 at the end of the post. Hope it helps! – felipe Jan 26 '20 at 01:07