0

I need to convert a string with bytes (string view) to byte object in Python.

string = input() # string = '\xff\x00B'
bs = samefunc(string) # typeof(bs) == bytes, len(bs) == 3
print(bs[0]) # b'\xff'
print(bs[1]) # b'\x00'
print(bs[2]) # b'B'

In my app the string input is so large the self parser will be very slow.

2
  • What do you mean by "the self parser"? Also, if bs is a bytes object, bs[0] will be 255, not b'\xff', if that matters. Commented Nov 16, 2016 at 12:56
  • You're right! bs is bytestring, and bs[0] == 255. Self parser is a selfwrite function, which parse string to normal symblos and \xXX constructions. Commented Nov 17, 2016 at 11:30

1 Answer 1

2

You can use eval (or ast.literal_eval, which is more secure if the input is not 100% in your hands):

s = input() # s = '\\xff\\x00B'
bs = eval("b'%s'" % s) # typeof(bs) == bytes, len(bs) == 3
print(bs[0]) # 255
print(bs[1]) # 0
print(bs[2]) # 66
Sign up to request clarification or add additional context in comments.

2 Comments

It's dont't working. Because s get from user input. And '\' is escaping. In program s == \\xff\\x00B`.
I've updated the answer to work if the input is escaped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.