Search code examples
pythonescaping

Misunderstanding removing escape characters using r before ""?


I have a misunderstanding of the use of r in print function to remove escape characters. Very basic example of what is not working for me below and one of several efforts I have made to remedy the situation:

print(r"I am trying to keep the backslash in the link using r  \www.home.com\")

SyntaxError: unterminated string literal (detected at line 19)

This is the error that is presented to me when I try to print to console. I have attempted different ways to end the string literal. Can someone help me to understand what is happening here and the logic.

I have attempted various fixes like:

print("\\www.home.com\\")

This does work, but in my head using r before the "" should work too.

Example of what works:
print(r"This string would print normally if I remove the last back slash \www.home.com")

Solution

  • "... I have a misunderstanding of the use of r in print function to remove escape characters. ..."

    This is called a raw string.

    Here are some excerpts, from the Python Documentation.

    The Python Language Reference – 2.4.1. String and Bytes literals

    "... Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters. ..."

    The Python Tutorial – 3.1.2. Text

    "... If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote ...

    ... There is one subtle aspect to raw strings: a raw string may not end in an odd number of \ characters; see the FAQ entry for more information and workarounds. ..."

    The reason your code doesn't work is because Python is interpreting the escape sequence as a literal value.
    The \ is essentially capturing the subsequent character.
    Thus, the ending \" is considered literal.

    Here is a similar question and answer.
    Why can't Python's raw string literals end with a single backslash?

    In this case, just use a regular string literal.

    print("I am trying to keep the backslash in the link using r  \www.home.com\\")