alexsuv
alexsuv

Reputation: 45

How to pass on python variables to markdown table?

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.

Upvotes: 1

Views: 3635

Answers (1)

felipe
felipe

Reputation: 8045

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)

Upvotes: 2

Related Questions