Evan Lin
Evan Lin

Reputation: 1322

Remove \x in string in python


I need get little endian random string via python.
Such as '0010' as 256 (without '\x')
Here is my code.

 import random
 import struct
 str1 = struct.pack('<Q', random.randint(1, 1000))
 #Ex: str1 = '\xc9\x02\x00\x00\x00\x00\x00\x00'

But I don't have any idea to convert this string to "C902000000000000" Please give any advise, thanks

Upvotes: 2

Views: 3219

Answers (4)

sajin
sajin

Reputation: 11

you can remove the "\x" from "\x0034" simply using this code if the ax variable contains the string

ax = ax.replace("\x00" , "")

then the \x00 will removed from the string

Upvotes: 0

glglgl
glglgl

Reputation: 91119

Another alternative, which is quite easy to type, is the following approach:

>>> import random
>>> import struct
>>> str1 = struct.pack('<Q', random.randint(1, 1000))
>>> str1.encode('hex')

Upvotes: 6

msvalkon
msvalkon

Reputation: 12077

struct.pack() returns you the bytes as specified by the format character. If you want the hexadecimal representation of the bytes, you'll need to convert them. You can use string formatting for that:

>>> import random
>>> import struct
>>> str1 = struct.pack('<Q', random.randint(1, 1000))
>>> "".join("{:02X}".format(ord(x)) for x in str1)
'C902000000000000'

Remember that in python, the hexadecimals are just strings, which prevents any meaningful manipulation. You can convert them to integers with ord():

>>> list(map(ord, str1)) # Or a list comprehension, [ord(x) for x in str1] 
[201, 2, 0, 0, 0, 0, 0, 0]

Upvotes: 1

zmo
zmo

Reputation: 24802

as an alternative to @msvalkon's solution, you can use the binascii package, which does the same, but more elegantly:

>>> import random
>>> import struct
>>> str1 = struct.pack('<Q', random.randint(1, 1000))
>>> import binascii
>>> binascii.hexlify(str1)
'c902000000000000'
>>> binascii.hexlify(str1).upper()
'C902000000000000'

Upvotes: 2

Related Questions