简体   繁体   English

我不懂python`print“”“`

[英]I do not understand python `print “”"`

I am trying to create a HTML form from a Python CGI script. 我正在尝试从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

The above of course does not work. 以上当然是行不通的。 I was under the false impression that whole print """ blah blah %s ...""" % string_var worked like C's printf function. print """ blah blah %s ...""" % string_var错误的印象,那就是整个print """ blah blah %s ...""" % string_var就像C的printf函数一样工作。 So what am I suppose to be doing here? 那我想在这里做什么?

I get this error message in my browser: 我在浏览器中收到以下错误消息:

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
print 'blah' % x, y

isn't interpreted as 不被解释为

print 'blah' % (x, y)

but rather as 而是

print ('blah' % x), y

Put parentheses around cgi.escape(message), script_name to pass a tuple as second argument to % . cgi.escape(message), script_name周围cgi.escape(message), script_name括号cgi.escape(message), script_name以将元组作为第二个参数传递给% Incidentally, this is one of the reasons you might want to prefer the str.format method over % . 顺便说一句,这是您可能更喜欢str.format方法而不是%的原因之一。

You need to wrap the format arguments in parenthesis. 您需要将格式参数包装在括号中。

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

When your code executes, the first thing that happens is it evaluates the expression 代码执行时,首先发生的事情是对表达式求值

long_string % cgi.escape(message)

Because there are two keys in the long string but only one value on the other side of the % operator, this is failing with the TypeError you see. 由于长字符串中有两个键,而%运算符的另一侧只有一个值,因此出现TypeError失败。

The solution is to wrap both values in a parentheses, so the second operand is interpreted as a tuple: 解决方案是将两个值都用括号括起来,因此第二个操作数被解释为元组:

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

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

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