How to treat a returned/stored string like a raw string in Python?
I am trying to .split()
a hex string i.e. '\xff\x00'
to get a list i.e. ['ff', '00']
This works if I split on a raw string literal i.e. r'\xff\x00'
usi开发者_StackOverflowng .split('\\x')
but not if I split on a hex string stored in a variable or returned from a function (which I presume is not a raw string)
How do I convert or at least 'cast' a stored/returned string as a raw string?
x = '\xff\x00'
y = ['%02x' % ord(c) for c in x]
print y
Output:
['ff', '00']
Here is a solution in the spirit of the original question:
x = '\xff\x00'
eval("r"+repr(x)).split('\\x')
It will return the same thing as r'\xff\x00'.split('\\x')
: ['', 'ff', '00']
.
精彩评论