我正在调试我的程序,我很困惑为什么我的一个语句的计算结果是错误的。我正在检查数组中倒数第二个索引(它是一个字符串)是否以“\”字符开头。我正在为post-script编写一个解释器,这有助于我确定用户是否定义了一个变量ex:\x。为我检查的if语句的计算结果为false,我无法找出原因。有什么想法吗?在
def psDef():
if(opstack[-2].startswith('\\')): # this is evaluating to false for some reason
name = opPop() #pop the name off the operand stack
value = opPop() #pop the value off the operand stack
define(name, value)
else:
print("Improper use of keyword: def")
def testLookup():
opPush("\n1")
opPush(3)
psDef()
if lookup("n1") != 3:
return False
return True
@麦迪已经指出了你的错误。如果您更改此行:
像是:
^{2}$你可能会得到你想要的。在
看看String literals
\n
的意思是ASCII Linefeed (LF)
。所以要在字符串文本中显示反斜杠,您需要用另一个反斜杠来转义反斜杠。在比如
opPush("\\n1")
希望这有帮助。在
默认情况下,Python接受字符串中的反斜杠转义序列。
\n
变成一个换行符。在要获得
\
和n
的实际序列,可以使用双反斜杠:'\\n'
或将字符串标记为“raw”:r'\n'
。在相关问题 更多 >
编程相关推荐