Add escape characters to a variable in Python
<p>I need to add an escape character to a variable which I'm appending to another string and have it apply its effects. This is what I have:</p>

<pre><code>h1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
h2 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']

h3 = list(itertools.product(h1, h2))
h4 = []

for item in h3:
    h4.append(''.join(item))

temp = r'\x' + str(h4[0]) + '\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
</code></pre>

<p>So if i have \xh I need the character with hex value hh but I can't seem to find anything in python that does this besides \x which I can't seem to use on variables.</p>

<p>Any suggestions?</p>

<p>A somewhat faster solution that repeated <code>int</code>/<code>chr</code> calls (assuming you're using more than just the first byte produced) is to create a complete hex string and parse it all at once:</p>

<pre><code>import itertools
import binascii

hexdigits = "123456789abcdef"
completehex = ''.join(map(''.join, itertools.product(hexdigits, repeat=2)))
completebytes = binascii.unhexlify(completehex)
</code></pre>

<p>This will bulk decode all the hexpairs into the raw byte values (the "escapes" you want), so <code>completebytes</code> would be <code>'\x00\x01\x02\x03...\xfd\xfe\xff'</code>.</p>

<p>Of course, for this specific case (if your real problem isn't just generating all possible bytes values in order), you could simplify it even further, because what you're doing is just generating all possible byte values:</p>

<pre><code># Py3
completebytes = bytes(range(256))

# On Py2, bytes is alias for str, so must use bytearray first to accept iterable of int
completebytes = bytes(bytearray(range(256)))
</code></pre>

<p>Or, just for fun, the fastest possible way abusing <code>maketrans</code>:</p>

<pre><code># Py3:
completebytes = bytes.maketrans(b'', b'')  # Add .decode('latin-1') if you really want str

# Py2:
import string
completebytes = string.maketrans('', '')
</code></pre>

python