Skip to content
Tech News
← Back to articles

Python string literals are kinda funny

read original more articles

pop quiz: which of these lines is valid python, and what's the content of the resulting string?

answer

the first line is a syntax error; the second line is valid. the content of the resulting string is asdf\'

the 'r' prefix makes it a raw string literal, so backslash escapes aren't interpreted in any special way. however, raw string literals are still lexed the same way as regular string literals, so they can't end in a backslash, since the following quote isn't treated as the end of the string, even though the quote isn't actually "escaped".

this was definitely originally done to simplify the implementation, which makes what i'm about to show you a lot funnier.