我不理解Python的print"""函数。

2024-05-15 22:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从Python CGI脚本创建一个HTML表单。你知道吗

script_name=os.environ.get('SCRIPT_NAME', '')

form = cgi.FieldStorage()
message = form.getvalue("message", "(no message)")

print """

  <p>Previous message: %s</p>

  <p>form

  <form method="post" action="%s">
    <p>message: <input type="text" name="message"/></p>
  </form>

</body>

</html>
""" % cgi.escape(message), script_name

以上当然不行。我的错误印象是 整个print """ blah blah %s ...""" % string_var像C的printf函数一样工作。 那我该在这里干什么呢?你知道吗

我在浏览器中收到以下错误消息:

Traceback (most recent call last):
  File "/usr/lib/cgi-bin/hello.py", line 45, in <module>
    """ % cgi.escape(message), script_name
TypeError: not enough arguments for format string

Tags: nameform脚本表单messagestringoshtml
3条回答
print 'blah' % x, y

不会被解释为

print 'blah' % (x, y)

而是作为

print ('blah' % x), y

cgi.escape(message), script_name周围加上括号,将元组作为第二个参数传递给%。顺便说一下,这是您可能希望使用^{}方法而不是%的原因之一。你知道吗

您需要将格式参数包装在括号中。你知道吗

print """ %s %s
do re me fa so la ti do
""" % (arg1(arg), arg2)

当代码执行时,发生的第一件事就是计算表达式

long_string % cgi.escape(message)

因为在长字符串中有两个键,但在%操作符的另一侧只有一个值,所以您看到的TypeError操作失败。你知道吗

解决方案是将两个值都用括号括起来,这样第二个操作数就被解释为元组:

long_string % (cgi.escape(message), script_name)

相关问题 更多 >