Python-2.7.13 syntaxerror

时间:2017-01-07 21:24:27

标签: python

当我在带命令的命令(第13行)下运行时,出现语法错误:

list1 = ["SuperMan", "BatMan", "The Mask", "SpiderMan"];

#print entire list
print "The list is: \n", list1

#reverse the list
list1.reverse()

#print entire list
print "\nThe reversed list is: \n", list1

#print the index of an object within the list
print "\nThe object "The Mask" is at index: ", list1.index("The Mask")

#remove object from the list
list1.remove("SpiderMan")

#print entire list
print "\nAfter Removing SpiderMan: \n", list1

运行文件

PS C:\Users\xxx> python listfun.py
  File "listfun.py", line 13
    print "\nThe object "The Mask" is at index: ", list1.index("The Mask")
                           ^
SyntaxError: invalid syntax

第13行,不喜欢The Mask之前和之后的引用 "面具" 如果我删除了引文,它将产生没有引号的答案,但这是不正确的。

list1 = ["SuperMan", "BatMan", "The Mask", "SpiderMan"];

#print entire list
print "The list is: \n", list1

#reverse the list
list1.reverse()

#print entire list
print "\nThe reversed list is: \n", list1

#print the index of an object within the list
print "\nThe object The Mask is at index: ", list1.index("The Mask")

#remove object from the list
list1.remove("SpiderMan")

#print entire list
print "\nAfter Removing SpiderMan: \n", list1

再次运行该文件

PS C:\Users\xxx> python listfun.py
The list is:
['SuperMan', 'BatMan', 'The Mask', 'SpiderMan']

The reversed list is:

['SpiderMan', 'The Mask', 'BatMan', 'SuperMan']

The object The Mask is at index:  1

After Removing SpiderMan:
['The Mask', 'BatMan', 'SuperMan']

4 个答案:

答案 0 :(得分:2)

此示例演示了有用的代码突出显示方式。如果字符串的某些部分有不同的颜色,那么出现问题:-) 要解决此问题,您需要仔细考虑String

中的引号
dateComponents.quarter = nil

应该是:

print "\nThe object "The Mask" is at index: ", list1.index("The Mask")

答案 1 :(得分:1)

在python中,只要你匹配它们,单引号和双引号就是可以互换的。您还可以选择使用带有三/双引号的多行字符串文字。

print "\nThe object "The Mask" is at index: ", list1.index("The Mask")

真正发生的事情是python试图将The解释为变量/单词。

要修复,您需要转义双引号或使用单引号,如下所示:

print "\nThe object 'The Mask' is at index: ", list1.index("The Mask")

或(使用转义字符):

print "\nThe object \"The Mask\" is at index: ", list1.index("The Mask")

或(用单引号交换双引号):

print '\nThe object "The Mask" is at index:,list1.index(“The Mask”)`

您还可以使用带有三引号或单引号的多行字符串文字,如下所示:

print '''\nThe object "The Mask" is at index: ''', list1.index("The Mask")

或(带双引号):

print """\nThe object "The Mask" is at index: """, list1.index("The Mask")

答案 2 :(得分:0)

双引号应该在第13行转义。

答案 3 :(得分:0)

如果您将报价与同类报价配对,则不需要逃避。它只是连接字符串,好像在*** Test Cases *** Calculation error [Template] Calculation should fail [setup] Set Test Variable ${counter} 0 kekkonen Invalid button 'k'. ${EMPTY} Invalid expression. 1 / 0 Division by zero. *** Keywords *** Calculation should fail [Arguments] ${expression} ${expected} ${error} = Should cause error C${expression}= Should be equal ${expected} ${error} # Using `BuiltIn` keyword [teardown] Counter Counter ${countr}= Get Variable Value ${counter} ${countr}= evaluate ${countr}+1 Set Test Variable ${counter} ${countr} 个对象之间有一个+

str