简体   繁体   English

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

[英]Adding List Elements to a Multi-line String

I'm trying to write a function that automatically sets up a HTML file using information from a list I've generated. 我正在尝试编写一个函数,该函数使用我生成的列表中的信息自动设置HTML文件。 This chunk below is part of a multi-line string. 下面的该块是多行字符串的一部分。

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

Extra_Data is a list of number ratings, so Extra_Data[9] = 7.2. Extra_Data是数字等级的列表,因此Extra_Data [9] = 7.2。 When I run the code I get the following error; 当我运行代码时,出现以下错误;

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

I'm not sure how else I could get this to work since str(Extra_Data[9]) doesn't do the trick and this is the only way I can think to get all of my listed data to be apart of the HTML code efficiently. 我不确定如何才能使它正常工作,因为str(Extra_Data [9])不能解决问题,这是我可以想到的将所有列出的数据与HTML代码分开的唯一方法有效率的。 Any help would be appreciated! 任何帮助,将不胜感激!

Thanks in advance. 提前致谢。

Python has the really handy string formatting method .format() , take a look here . Python具有真正方便的字符串格式化方法.format() ,请在此处查看 All you'd need to do is something along the lines of: 您需要做的只是以下几方面的事情:

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

print a

The numbers in swirly brackets {n} are the placeholders for the argument at the nth index of the .format() function. 旋括号{n}中的数字是.format()函数第n个索引处参数的占位符。

To take this one step further, you could iterate over your data lists to create each row programatically: 为了更进一步,您可以遍历数据列表以编程方式创建每一行:

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])

So, in my crazy attempts to solve this issue. 因此,在我疯狂地尝试解决此问题的过程中。 I changed the line to this; 我改变了这一行。 <th>"""+str(float(Extra_Data[9]))+"""</th> and then it worked. <th>"""+str(float(Extra_Data[9]))+"""</th> ,然后就可以了。 I have no idea why so I changed it back to the original line and then it continued to work. 我不知道为什么,所以我将其更改回原始行,然后继续工作。 I am so very confused as to why this has happened but as it stands now, my code works and it's the same as it did when it didn't work. 对于为什么会发生这种情况,我感到非常困惑,但是就目前而言,我的代码可以正常工作,并且与不工作时的代码相同。 I'm not sure why or how. 我不确定为什么或如何。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM