【问题标题】:How to pass on python variables to markdown table?如何将python变量传递给markdown表?
【发布时间】:2020-05-11 20:25:30
【问题描述】:

我的python代码:

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

fish='salmon'
print fish

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

但是餐桌上的鱼并没有被鲑鱼取代。我尝试了引号、单曲折等。

一些讨论似乎暗示我需要安装更多的扩展,我随机尝试了。

我想我缺乏一个干净的方法来解决这个问题。

【问题讨论】:

标签: python python-2.7 markdown


【解决方案1】:

你可以像这样使用f-strings

hello = "Hey"
world = "Earth"

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

print(test)

输出:

Hey Earth

只需在字符串前添加f,并使用大括号 ({python-code}) 将 Python 代码插入字符串(在上面的示例中,两个变量分别名为 helloworld)。


以您的代码为例:

from markdown import markdown

fish = "salmon"

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

输出:

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

如果您使用的是 Python 2.7,则可以使用 str.format() 函数:

from markdown import markdown

fish = "salmon"

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

html = markdown(s, extensions=["tables"])
print(html)

【讨论】:

  • 我需要使用markdown模块来创建一个表并用变量填充表。所以我想这更像是一个降价问题。
  • 我认为您错过了答案的重点。你可以使用f-strings来满足你的需要——{{fish}}标签你可以将它更改为{fish},如果你在字符串的开头添加ff""" ... text ... """),你的问题应该小心的。
  • 您的代码本身有效。但是我需要使用 markdown 模块创建一个表。对不起,如果我仍然没有抓住重点。
  • 编辑了我的答案,以便您了解它如何与 markdown 模块一起使用。 markdown 模块没有指定任何可以传递变量以在 docs 中填充字符串的方式——这是您在使用 markdown 之前可能必须做的事情。
  • 我看到你粘贴了带有降价的代码,谢谢。它对我不起作用,可能是因为我的 python 版本太旧(2.7)。我在 imac 上,它带有默认的 v2.7。再次感谢您!
猜你喜欢
  • 1970-01-01
  • 2011-11-23
  • 2011-02-17
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多