字符串计算中的Python反斜杠

2024-09-30 05:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在调试我的程序,我很困惑为什么我的一个语句的计算结果是错误的。我正在检查数组中倒数第二个索引(它是一个字符串)是否以“\”字符开头。我正在为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

Tags: thenamefalseifvaluestackdef语句
3条回答

@麦迪已经指出了你的错误。如果您更改此行:

 opPush("\n1")

像是:

^{2}$

你可能会得到你想要的。在

看看String literals

The backslash (\) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.

\n的意思是ASCII Linefeed (LF)。所以要在字符串文本中显示反斜杠,您需要用另一个反斜杠来转义反斜杠。在

比如opPush("\\n1")

希望这有帮助。在

默认情况下,Python接受字符串中的反斜杠转义序列。\n变成一个换行符。在

要获得\n的实际序列,可以使用双反斜杠:'\\n'或将字符串标记为“raw”:r'\n'。在

相关问题 更多 >

    热门问题