Why can’t raw strings (r-strings) end with a backslash in Python?


The r in r-strings means raw strings. String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.

When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"\n" consists of two characters −

  • a backslash and
  • a lowercase 'n'.

String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r""" is a valid string literal consisting of two characters −

  • a backslash and
  • a double quote;

The r"" is not a valid string literal. Specifically, a raw string cannot end in a single backslash. A single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation.

For Windows pathnames, the Windows system calls accept forward slashes too −

f = open("/mydir/demo.txt")

Pathname for a DOS command −

dir = r"\this\is\my\dos\dir" ""
dir = r"\this\is\my\dos\dir\ "[:-1]
dir = "\this\is\my\dos\dir"

Updated on: 20-Sep-2022

871 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements