python 2.7 TypeError:一元+的错误操作数类型:'str'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29880136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 05:07:34  来源:igfitidea点击:

python 2.7 TypeError: bad operand type for unary +: 'str'

pythonpython-2.7

提问by Marco Dinatsoli

this is my code

这是我的代码

message = "From: %s\r\n" % fromaddr
        + "To: %s\r\n" % toaddrs
        + "CC: %s\r\n" % ",".join(cc)
        + "Subject: %s\r\n" % message_subject
        + "\r\n" 
        + msg

i am getting this error:

我收到此错误:

    + "To: %s\r\n" % toaddrs
TypeError: bad operand type for unary +: 'str'

may you help please

你能帮忙吗

采纳答案by Matthew Drury

To fix your problem, wrap the whole expression for message in parenthesies:

要解决您的问题,请将 message 的整个表达式用括号括起来:

message = (
      "From: %s\r\n" % fromaddr
    + "To: %s\r\n" % toaddrs
    + "CC: %s\r\n" % ",".join(cc)
    + "Subject: %s\r\n" % message_subject
    + "\r\n" 
    + msg
)

The error message python is giving is quite helpful. Unary operations are those with exactly one argument. + can be used as a unary operation in python,

python 给出的错误消息非常有帮助。一元运算是那些只有一个参数的运算。+ 可以用作python中的一元运算,

x = + 2

is valid code. What's happening in your snippet is that the first line:

是有效代码。您的代码段中发生的事情是第一行:

message = "From: %s\r\n" % fromaddr

is being interpreted as a full assignment statement. The next line starts a new statement, but is incomplete.

被解释为完整的赋值语句。下一行开始一个新的语句,但不完整。