Hexadecimal file is loading with 2 back slashes before each byte instead of one
<p>I have a hex file in this format: <code>\xda\xd8\xb8\x7d</code></p>

<p>When I load the file with Python, it loads with two back slashes instead of one.</p>

<pre><code>with open('shellcode.txt', 'r') as file:
    shellcode = file.read().replace('\n', '')
</code></pre>

<p>Like this: <code>\\xda\\xd8\\xb8\\x7d</code></p>

<p>I've tried using <code>hex.replace("\\", "\")</code>, but I'm getting an error</p>

<blockquote>
  <p>EOL while scanning string literal</p>
</blockquote>

<p>What is the proper way to replace <code>\\</code> with <code>\</code>?</p>

<p>Backshlash (<code>\</code>) is an escape character. It is used for changing the meaning of the character(s) following it.</p>

<p>For example, if you want to create a string which contains a quote, you have to escape it:</p>

<pre><code>s = "abc\"def"
print s  # prints: abc"def
</code></pre>

<p>If there was no backslash, the first quote would be interpreted as the end of the string.</p>

<p>Now, if you really wanted that backslash in the string, you would have to escape the bacsklash using another backslash:</p>

<pre><code>s = "abc\\def"
print s  # prints: abc\def
</code></pre>

<p>However, if you look at the representation of the string, it will be shown with the escape characters:</p>

<pre><code>print repr(s)  # prints: 'abc\\def'
</code></pre>

<p>Therefore, this line should include escapes for each backslash:</p>

<pre><code>hex.replace("\\", "\")  # wrong

hex.replace("\\\\", "\\")  # correct
</code></pre>

<p>But that is not the solution to the problem!</p>

<p>There is no way that <code>file.read().replace('\n', '')</code> introduced additional backslashes. What probably happened is that OP printed the representation of the string with backslashes (<code>\</code>) which ended up printing escaped backslashes (<code>\\</code>).</p>

python escaping hex