Convert a converted bytes to str to bytes python

Viewed 67

How convert a converted bytes to str to bytes python Simple:

re="Xin chào"
print(re.encode("utf-8"))
# OUTPUT : b'Xin ch\xc3\xa0o'

But i have a str like

print(new_str)
# OUTPUT : Xin ch\xc3\xa0o 

So how can I decode "new_str" var

3 Answers

Do you meen "decode"? This is source

string = r"Xin ch\xc3\xa0o"
exec(f"global string;string=b'{string}'")
string = string.decode("utf-8")
print(string)

I didn't exactly understand what you were trying to do, but if you wanna encode a string or a variable use encode() function:

string = "string"
en = string.encode()
print(en)

for example: if the string is "Hello", the output would be b'Hello'.

and if you wanna decode:

print (string.decode('utf8', 'strict'))

Let's assume your new_str var contains b'Xin ch\xc3\xa0o' so,

new_str = b'Xin ch\xc3\xa0o'

You can convert it back to Xin chào using the decode() method.

new_str = b'Xin ch\xc3\xa0o'
print(new_str.decode())

The output will be, Xin chào

Related