0

I saw here https://stackoverflow.com/a/35651859/6824121 that you can launch python script directly in your terminal in windows like this:

> python -c exec("""import sys \nfor r in range(10): print('rob') """)

Which works perflectly.

I tried to launch this command:

> python -c exec("""test = r'C:\Users\alexa\Downloads\_internal'""")

And I got error:

File "<string>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 11-12: truncated \UXXXXXXXX escape

As in this question "Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

But I used raw string so I don't know why I still got the error.

What am I missing here ?

I'm using Python 3.6.8 even though I don't think this is related to the version of python.

Lenny4
  • 1,215
  • 1
  • 14
  • 33
  • 4
    `"""..."""` is not a raw string, you need to also prepend that with `r`, i.e. `r"""test = r'C:\Users\alexa\Downloads\_internal'"""` – metatoaster May 23 '23 at 04:17

1 Answers1

0

For this code to work properly, you have to prefix the string with the character r. This is crucial, as it turns the string into a raw string. This is needed, as this treats the backslash character (/) as a literal character. This is why this code will work:

> python -c exec(r"""test = r'C:\Users\alexa\Downloads\_internal'""")

This is also why the r character is needed inside of the string as well, as when that code is executed it will be needed for the same purpose.

You can also (though I do not recommend this) use double backslashes, which escape the first backslash. This is hard to read, however, and makes it easy to make mistakes. For example:

> python -c exec("""test = r'C:\\Users\\alexa\Downloads\\_internal'""")

In the end I would recommend the raw string, however.

Hope this helps.

radio
  • 93
  • 7