Python - ordinary literals
I don't understand how string literals work. I know that when used, r
it ignores all special features, for example, when executed, \n
it treats it as \ n and not as a newline. but then i tried to do this:
x = r'\'
and he said SyntaxError: EOL while scanning string literal
, not '\'
why? did I understand it correctly? and also what explains it:
print r'\\' # gives '\\'
print r'\\\' # gives SyntaxError
source to share
The only way to insert one quote in a line starting with one quote is to avoid it. Thus, both raw and regular string literals will allow you to escape quote characters when you have a raw backslash followed by a quote character. Due to the requirement that there be a way to express single (or double) quotes within string literals that start with single (or double) quotes, the string literal is '\'
not legal whether you use a regular or regular string literal.
To get an arbitrary string with an odd number of literal backslashes, I believe the best way is to use regular string literals. This is because trying to use it r'\\'
will work, but it will give you a string with two backslashes instead of one:
>>> '\\' # A single literal backslash.
'\\'
>>> len('\\')
1
>>> r'\\' # Two literal backslashes, 2 is even so this is doable with raw.
'\\\\'
>>> len(r'\\')
2
>>> '\\'*3 # Three literal backslashes, only doable with ordinary literals.
'\\\\\\'
>>> len('\\'*3)
3
This answer is only intended to complement another.
source to share
In the original literal, the backslash will escape the quote character that defines the string.
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; r" \ "is not a valid string literal (even a raw string cannot end with an odd number of backslashes). the line cannot be terminated with a single backslash (because the backslash will escape the next quote character.) Note also that a single backslash followed by a newline is interpreted as the two characters as part of the line, not as a continuation of the line.
From docs
source to share