I have come across a string constant that is preceded by a letter r
, of the following form:
a_expresion = r"\[(.*?)\]"
I haven't seen this before and I wonder
- what does the
r
preceding the string mean? - what varies between
'cadena'
andr'cadena'
?
String constants can be preceded by one
r
that stands for raw ; something like crude or literal in Spanish.A literal string constant , as I'll call it, has a slightly different syntax than a regular string constant . in which the backslash
\
character has no special meaning, in other words, it is not the start of an escape sequence, but its value is taken literally. In a string literal constant ,\n
it is exactly that,\n
and notCRLF
or enter,\t
not tab, etc.As far as I know, the only exception to this rule is when the backslash comes before the quote, which would otherwise terminate the string.
This avoids having to put double backslashes to avoid starting escape sequences, as you would have to do in a normal string constant .
This variant is very convenient when writing constants that represent:
\
Not only are they easier to write, but they look less cluttered , making them easier to inspect and debug.
Let's compare some examples, in both variants:
The expression in your question, given that it only has a couple of characters, is not so heavy in its normal form , but I think the following ones make it more than clear that it is convenient to write them literally .
Regarding your final question, between
'cadena'
andr'cadena'
there is no variation, since it does not contain any character\
, however, this does vary:the output is: