Read regexes from file and avoid or undo escaping
<p>I want to read regular expressions from a file, where each line contains a regex:</p>

<pre><code>lorem.*
dolor\S*
</code></pre>

<p>The following code is supposed to read each and append it to a list of regex strings:</p>

<pre><code>vocabulary=[]
with open(path, "r") as vocabularyFile:
    for term in vocabularyFile:
        term = term.rstrip()
        vocabulary.append(term)
</code></pre>

<p>This code seems to escape the <code>\</code> special character in the file as <code>\\</code>. How can I either avoid escaping or unescape the string so that it can be worked with as if I wrote this?</p>

<pre><code>regex = r"dolor\S*"
</code></pre>

<p>You are getting confused by <em>echoing the value</em>. The Python interpreter echoes values by printing the <code>repr()</code> function result, and this makes sure to escape any meta characters:</p>

<pre><code>&gt;&gt;&gt; regex = r"dolor\S*"
&gt;&gt;&gt; regex
'dolor\\S*'
</code></pre>

<p><code>regex</code> is still an 8 character string, not 9, and the single character at index 5 is a single backslash:</p>

<pre><code>&gt;&gt;&gt; regex[4]
'r'
&gt;&gt;&gt; regex[5]
'\\'
&gt;&gt;&gt; regex[6]
'S'
</code></pre>

<p>Printing the string writes out all characters verbatim, so no escaping takes place:</p>

<pre><code>&gt;&gt;&gt; print(regex)
dolor\S*
</code></pre>

<p>The same process is applied to the contents of containers, like a <code>list</code> or a <code>dict</code>:</p>

<pre><code>&gt;&gt;&gt; container = [regex, 'foo\nbar']
&gt;&gt;&gt; print(container)
['dolor\\S*', 'foo\nbar']
</code></pre>

<p>Note that I didn't echo there, I printed. <code>str(list_object)</code> produces the same output as <code>repr(list_object)</code> here.</p>

<p>If you were to print individual elements from the list, you get the same unescaped result again:</p>

<pre><code>&gt;&gt;&gt; print(container[0])
dolor\S*
&gt;&gt;&gt; print(container[1])
foo
bar
</code></pre>

<p>Note how the <code>\n</code> in the second element was written out as a newline now. It is for <em>that reason</em> that containers use <code>repr()</code> for contents; to make otherwise hard-to-detect or non-printable data visible.</p>

<p>In other words, your strings do <em>not</em> contain escaped strings here.</p>

python regex python-3.x escaping