【问题标题】:syntaxerror: "unexpected character after line continuation character in python" math语法错误:“python 中的续行字符后出现意外字符”数学
【发布时间】:2011-12-09 03:59:24
【问题描述】:

我在创建这个 Python 程序时遇到问题,我正在创建这个程序来进行数学运算、计算等解决方案,但我收到了语法错误:“python 中的行继续符后出现意外字符”

这是我的代码

print("Length between sides: "+str((length*length)*2.6)+" \ 1.5 = "+str(((length*length)*2.6)\1.5)+" Units")

我的问题是 \1.5 我试过 \1.5 但它不起作用

使用python 2.7.2

【问题讨论】:

    标签: python math syntax continuation


    【解决方案1】:

    除法运算符是/,而不是\

    【讨论】:

    • 我切换到使用 *0.666666667 然后我看到了这个......我可能会坚持我现在写的内容。
    【解决方案2】:

    反斜杠\ 是错误消息所说的行继续字符,在它之后,只允许换行符/空格(在下一个非空格继续“中断”行之前。

    print "This is a very long string that doesn't fit" + \
          "on a single line"
    

    在字符串之外,反斜杠只能以这种方式出现。对于除法,您需要一个斜杠:/

    如果您想在字符串中逐字写入反斜杠,请将其转义:"\\"

    在您的代码中,您使用了两次:

     print("Length between sides: " + str((length*length)*2.6) +
           " \ 1.5 = " +                   # inside a string; treated as literal
           str(((length*length)*2.6)\1.5)+ # outside a string, treated as line cont
                                           # character, but no newline follows -> Fail
           " Units")
    

    【讨论】:

      【解决方案3】:

      你必须在连续字符后按回车

      注意:连续字符后的空格会导致错误

      cost = {"apples": [3.5, 2.4, 2.3], "bananas": [1.2, 1.8]}
      
      0.9 * average(cost["apples"]) + \ """enter here"""
      0.1 * average(cost["bananas"])
      

      【讨论】:

      • 哇 - 这么小的信息块 - 花了很多时间试图找出代码不起作用的原因;不知道“在续行字符后立即按 Enter”,非常感谢!
      【解决方案4】:

      除法运算符是/,而不是\

      此外,反斜杠在 Python 字符串中具有特殊含义。要么用另一个反斜杠转义它:

      "\\ 1.5 = "`
      

      或使用原始字符串

      r" \ 1.5 = "
      

      【讨论】:

        【解决方案5】:

        好吧,你想做什么?如果要使用除法,请使用“/”而不是“\”。 如果是别的,请详细解释一下。

        【讨论】:

          【解决方案6】:

          正如其他人已经提到的:除法运算符是 / 而不是 **。 如果您想在字符串中打印 ** 字符,则必须对其进行转义:

          print("foo \\")
          # will print: foo \
          

          我想打印你想要的字符串我想你需要这个代码:

          print("Length between sides: " + str((length*length)*2.6) + " \\ 1.5 = " + str(((length*length)*2.6)/1.5) + " Units")
          

          而这个是上面的一个更易读的版本(使用格式方法):

          message = "Length between sides: {0} \\ 1.5 = {1} Units"
          val1 = (length * length) * 2.6
          val2 = ((length * length) * 2.6) / 1.5
          print(message.format(val1, val2))
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-08-08
            • 2017-08-22
            • 2015-01-17
            • 1970-01-01
            相关资源
            最近更新 更多