【问题标题】:Python: How to insert a line in a multi-line string?Python:如何在多行字符串中插入一行?
【发布时间】:2017-12-15 01:03:38
【问题描述】:

我正在尝试制作一个简单的网站演示,但我在使用 python 编辑 html 时遇到了一些麻烦。以下是我定义的用于存储 html 的字符串(不完整,因为它太长了)。我想写一个在特定条件下会抛出错误的函数,但是我不知道如何在字符串“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>

我想在这两行之间的空白处插入“有错误”这一行:

<td class="error">

</td>

注意字符串中有两个这个组。如何使用 Python 在第一组中插入“有错误”?谢谢。

【问题讨论】:

标签: python html insert multilinestring


【解决方案1】:

python 使用 C 风格的格式字符串。

page="""<html>
       ......
      <td class="error">
         %s
      </td>
    </tr>"""  % "There was an error"

或者,您可以使用 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) 也值得研究。

对于 Jinja2:

pip install Jinja2

在python中

from jinja2 import Template
page = Template("""<html> .... 
<td class="error">{{x}}</td>
""")
page.render(x="There was an error")

【讨论】:

  • 感谢您的回答。我尝试了第一种方法,它奏效了。但是当我尝试self.response.out.write(page % "There was an error")(self 继承自 webapp2.RequestHandler) 时,打印出“%s”而不是错误消息。为什么我不能这样做?
  • 这很奇怪。我必须看到更多才能复制,如果 % 不能消耗所有参数或没有得到足够的参数,它应该会爆炸。
猜你喜欢
  • 2011-10-19
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-04
  • 1970-01-01
  • 2012-02-23
相关资源
最近更新 更多