Note that there are some explanatory texts on larger screens.

plurals
  1. POpython "re" package, strange phenomenon with "raw" string
    primarykey
    data
    text
    <p>I am seeing the following phenomenon, couldn't seem to figure it out, and didn't find anything with some search through archives:</p> <p>if I type in:</p> <pre><code>&gt;&gt;&gt; if re.search(r'\n',r'this\nis\nit'):&lt;br&gt; ... print 'found it!'&lt;br&gt; ... else:&lt;br&gt; ... print "didn't find it"&lt;br&gt; ... </code></pre> <p>I will get:</p> <pre><code>didn't find it! </code></pre> <p>However, if I type in:</p> <pre><code>&gt;&gt;&gt; if re.search(r'\\n',r'this\nis\nit'):&lt;br&gt; ... print 'found it!'&lt;br&gt; ... else:&lt;br&gt; ... print "didn't find it"&lt;br&gt; ... </code></pre> <p>Then I will get:</p> <pre><code>found it! </code></pre> <p>(The first one only has one backslash on the r'\n' whereas the second one has two backslashes in a row on the r'\\n' ... even this interpreter is removing one of them.)<br><br> I can guess what is going on, but I don't understand the official mechanism as to why this is happening: in the first case, I need to escape two things: both the regular expression and the special strings. "Raw" lets me escape the special strings, but not the regular expression.<br><br> But there will never be a regular expression in the second string, since it is the string being matched. So there is only a need to escape once. <br><br> However, something doesn't seem consistent to me: how am I supposed to ensure that the characters <em>REALLY ARE</em> taken literally in the first case? Can I type rr'' ? Or do I have to ensure that I escape things twice? On a similar vein, how do I ensure that a variable is taken literally (or that it is <em>NOT</em> taken literally)? E.g., what if I had a variable tmp = 'this\nis\nmy\nhome', and I really wanted to find the literal combination of a slash and an 'n', instead of a newline?<br><br> Thanks!<br>Mike</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload