I am taking a byte as input b'\xe2I4\xdd\r\xe5\xfcy^4\xd5'
but it gets converted into string.
so when i am to trying to convert this string to byte it is again manipulating it and giving me output as:
b"b'\\xe2I4\\xdd\\r\\xe5\\xfcy^4\\xd5'"
My desired output is that when i provide b'\xe2I4\xdd\r\xe5\xfcy^4\xd5' it convert it into byte as it is without manipulating it or adding any character or symbol.
Any resource or reference will be helpful.
Thanks In Advance
You could pass the value of input()
to eval()
function. The function eval()
directly evaluates a string as if it were directly executed in Python. Although it might feel like a best feature at first but due to the same reason it is pretty much unsafe to use it within any production-level application, since, the user can execute any code using that which might cause a lot of problems.
You can use a safer alternative to eval()
which is ast.literal_eval()
. This function evaluates a given string as Python literals (like string, numbers, bytes object, etc.). In case if a string does not contain any literal (like function calls, object creation, assignment, etc.), this function throws an error. Enough about that let's see how you could get this working.
import ast
user_input = input()
eval_expr = ast.literal_eval(user_input)
If you want to check if the input is a bytes
literal, you could use the isinstance
function to check and then perform required action.
# Optional: Handle if `eval_expr` is not a `bytes` literal
if not isinstance(eval_expr, bytes):
...
So, all you need to do is import the module ast
first. Then take the user's input. Thereafter pass this input string to ast.literal_eval()
function to evaluate the string.