0

Possible Duplicate:
Why is ‘\x’ invalid in Python?

realId = 'Test'
id = ""
for x in realId:
 id += '\x'+str(ord(x))
print id

Honestly I'm pretty new to python and askii conversion so this should be a quick answer. I'm getting an error when creating this string, would anyone like to point me in the right direction?

Community
  • 1
  • 1
Echocage
  • 250
  • 2
  • 4
  • 14

3 Answers3

2

Is this what you are looking for?

>>> realId = 'Test'
>>> id = ""
>>> for x in realId:
...     id += r'\x'+str(ord(x))
... 
>>> print id
\x84\x101\x115\x116
Fabian
  • 4,002
  • 19
  • 32
0

Are you looking for this?

realId = 'Test'
id = ""
for x in realId:
   id += r'\x%02x' % ord(x)
print id  # \x54\x65\x73\x74
georg
  • 204,715
  • 48
  • 286
  • 369
0

What you're trying to do isn't possible, because \x__ is a part of the string syntax, and cannot be done dynamically. However, you can use chr to get the equivalent characters:

>>> chr(0x01)
'\x01'
>>> chr(0x41)
'A'
Sanqui
  • 186
  • 4