0

Every time I try to run this program I got from this tutorial: https://www.youtube.com/watch?v=rioXu6EBN0s (minute 16), I get this error:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \UXXXXXXXX escape.

This is the code that I wrote:

my_variable = "<html><head><title>My HTML File</title></head><body><h1>Hello world!</h1></body></html>"

my_html_file = open("\Users\hp\Desktop\Code\Python testing\CH\my_html_file.html", "w")

my_html_file.write(my_variable)

Does anyone know why I'm getting the error and how I can fix it?

Thanks in advance!

1 Answer 1

1

The \U at the beginning of the string tells Python that you are trying to enter a numeric Unicode character. You don't follow it up with a number, so you get an error.

Stick an r in front of the string literal to prevent \ from being interpreted specially:

open(r"....")

In the future, please put the code and the error message in the question.

4
  • Thank you very much, I will keep that in mind for future posts. Is this r trick only for this example or can I use it for other misinterpretations? Thanks in advance!
    – I. Wewib
    Feb 12, 2017 at 2:40
  • Yes, you can use it in many places. It's very convenient when you have a lot of backslashes in a string, like a Windows file path or a regular expression. (Although, for future reference, Windows also accepts forward slashes, so you could just use those instead.)
    – kindall
    Feb 12, 2017 at 2:41
  • Without the code and error message, how is anyone supposed to find this question and answer in the future? Feb 12, 2017 at 2:41
  • Thank you very much for the help. I'll edit the post.
    – I. Wewib
    Feb 12, 2017 at 2:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.