Question

Just a quick silly question. How do I write a trailing slash in a raw string literal?

r = r'abc\'  # syntax error
r = r'abc\\' # two slashes: "abc\\"
Was it helpful?

Solution

You can't. A raw string literal can't end with an odd number of backslashes (langref; last paragraph of that section). You can, howerver, write a raw string literal without the backslash, and write the final backslash as an ordinary string literal:

r = r'abc' '\\'

Adjacent string literals are implicitly concatenated by the parser.

OTHER TIPS

Raw string literals are parsed in exactly the same way as ordinary string literals; it’s just the conversion from string literal to string object that’s different. This means that all string literals must end with an even number of backslashes; otherwise, the unpaired backslash at the end escapes the closing quote character, leaving an unterminated string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top