dotancohen
dotancohen

Reputation: 31521

How to create a representable hex int by string concatenation?

Consider:

>>> a = '\xe3'
>>> a
'ã'
>>> a.encode('cp1252')
b'\xe3'

I would like to recreate the a variable if the user input the string e3:

>>> from_user = 'e3'
>>> a = '\x' + from_user
  File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: end of string in escape sequence
>>> a = '\\x' + from_user
>>> a
'\\xe3'
>>> a.encode('cp1252')
b'\\xe3'

With the string from_user, how might I create the a variable such that I could use it just like I did in the first example?

Upvotes: 0

Views: 75

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477570

This should give you an idea:

unichr(int('e3', 16)).encode('cp1252')

Upvotes: 1

Related Questions