Python:如何在多行字符串中插入一行? [英] Python: How to insert a line in a multi-line string?
问题描述
我试图做一个简单的网站演示,并且使用python编辑html时遇到了一些麻烦。以下是我定义的用于存储html的字符串(因为它太长而不完整)。我想写一个函数,在某些情况下会抛出一个错误,但我不知道如何在字符串page中插入一行。
I'm trying to make a simple website demo and I have some trouble editing the html using python. The following is the string I defined to store the html (not complete because it's too long). I want to write a function that will throw a error under a certain condition, but I don't know how to insert a line in the string "page".
page="""
<html>
<head>
<title>Sign up</title>
<style type="text/css">
.label {text-align: right}
.error {color: red}
</style>
</head>
<body>
<h2>Sign up</h2>
<form method="post">
<table>
<tr>
<td class="label">
Username
</td>
<td>
<input type="text" name="username" value="">
</td>
<td class="error">
</td>
</tr>
<tr>
<td class="label">
Password
</td>
<td>
<input type="password" name="password" value="">
</td>
<td class="error">
</td>
</tr>
我想在这两行之间的空白处插入There is an error行:
I want to insert the line "There is an error" in the blank between these two lines:
<td class="error">
</td>
注意这个字符串中有两个这个组。如何在第一组中使用Python插入有错误?谢谢。
Note there are two of this group in the string. How can I insert "There is an error" in the first group using Python? Thanks.
推荐答案
python使用C风格的格式字符串。
python uses C style format strings.
page="""<html>
......
<td class="error">
%s
</td>
</tr>""" % "There was an error"
<或者,您可以使用python string.format作为
alternatively, you can use python string.format as
"fooo {x}".format(x="bar").
请参阅( https://docs.python.org/2/library/string.html );
jinja如果你有时间的话,它是一款出色的模板引擎。 Genshi( https://genshi.edgewall.org/wiki/GenshiTutorial )值得研究
jinja is an excellent template engine if you've got the time. Genshi (https://genshi.edgewall.org/wiki/GenshiTutorial) is worth looking into as well.
对于Jinja2:
pip install Jinja2
in python
in python
from jinja2 import Template
page = Template("""<html> ....
<td class="error">{{x}}</td>
""")
page.render(x="There was an error")
这篇关于Python:如何在多行字符串中插入一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!