-1

I am debugging my program and I am confused as to why one of my statements is evaluating to false. I am checking if the second to last index in my array (which is a string) starts with '\' character. I am writing an interpreter for post script and so this helps me determine whether or not the user is defining a variable ex: \x. My if statement that is checking this for me is evaluating to false and I cannot figure out why. Any thoughts?

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
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
CodySig
  • 174
  • 1
  • 4
  • 15
  • 3
    `"\n1"` does not start with a backslash. It starts with a newline character, represented in the string literal as `\n`. – user2357112 Feb 13 '17 at 03:27

3 Answers3

2

Have a look at 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 means ASCII Linefeed (LF).So to display a backslash in a string literal you need to escape the backslash with another backslash.

like opPush("\\n1")

Hope this helps.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
McGrady
  • 10,869
  • 13
  • 47
  • 69
0

@McGrady has already pointed out your error. If you change this line:

 opPush("\n1")

to something like:

 opPush("\\n1")

you'll probably get what you want.

aghast
  • 14,785
  • 3
  • 24
  • 56
0

By default Python accepts backslash escape sequences in strings. \n becomes a newline.

To get an actual sequence of \ and n you can use a double backslash: '\\n' or mark the string as "raw": r'\n'.

Klaus D.
  • 13,874
  • 5
  • 41
  • 48