python - 将列表元素添加到多行字符串

标签 python

我正在尝试编写一个函数,该函数使用我生成的列表中的信息自动设置 HTML 文件。下面的这个 block 是多行字符串的一部分。

`"""...
<tr>
  <td>10</td>
  <th>"""+str(List_Data[9])+"""</th>
  <th>"""+str(Extra_Data[9])+"""</th>
</tr>
</table>
..."""`

Extra_Data 是数字评级列表,因此 Extra_Data[9] = 7.2。当我运行代码时,出现以下错误;

`<th>"""+str(Extra_Data[9])+"""</th>
TypeError: can only concatenate str (not "list") to st`

我不知道我还能如何让它工作,因为 str(Extra_Data[9]) 不起作用,这是我能想到的将所有列出的数据分开的唯一方法高效地编写 HTML 代码。任何帮助将不胜感激!

提前致谢。

最佳答案

Python 有非常方便的字符串格式化方法 .format(),看看 here 。您需要做的就是:

a = """
<tr>
  <td>10</td>
  <th>{0}</th>
  <th>{1}</th>
</tr>
</table>
""".format(List_Data[9], Extra_Data[9])

print a

漩涡括号 {n} 中的数字是 .format() 函数第 n 个索引处的参数的占位符。

要更进一步,您可以迭代数据列表以编程方式创建每一行:

Table_Array = list()

for index, value in enumerate(List_Data):
    Table_Array.append("""
                       <tr>
                           <td>{0}</td>
                           <th>{1}</th>
                           <th>{2}</th>
                       </tr>
                       """.format(index, List_Data[index], Extra_Data[index])

关于python - 将列表元素添加到多行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52812647/

相关文章:

python - 交替开关开/关?

python - 用 Python 编程经典 15 谜题

python - 替换 pandas 系列中的值,其中要替换的元素包含要替换的元素的一部分

python - 图中图

python - django 将 '/' 重定向到平面页面

python - 删除重复项并找到唯一的子列表

python - 是否可以使用字典中的数据绘制线条?

python - python中的“否定”模式匹配

python :[Error 3] The system cannot find the path specified:

python - Numba:双重释放或损坏(!prev)中止(核心转储)