Convert a byte variable into a string?

Asked

Viewed 750 times

-1

Good afternoon liked to convert a byte variable into string.

I have the following code;

print(str.encode(frase))

which gives the following output;

b'Ola'

and wanted before;

Ola

I found a way to convert but only with a string not with a variable;

b"abcde".decode("utf-8") 

My question is how I use this code with a variable?

  • What do you mean by that? Like having that name as a variable? Try using eval() and exec().

  • what I wanted to do is this for example; b "abcde". Decode("utf-8") and put in "abcde" a variable and make the conversion

  • 1

    Your question makes no sense... If the variable contains bytes, just use the Decode method normally. Type: meus_bytes = b'Ola' afterward meus_bytes.decode("utf-8")...

2 answers

1


In Python, the values that "are inside" the variables (technically "associated with names") are all objects - just as the literals typed directly in the program are also objects. Literals are, for example, what you’re calling a string - all the values that are typed in the program - be b"maca", numbers like 123.45, etc.....

For language, when we use a method of an object type, whether the object was typed directly into the program code, or a literal, or whether it is in a variable.

That is to say:

meus_bytes = b"frase de teste"
minha_string = meus_bytes.decode("utf-8")  
  • The method decode with the notation of ., is called with the . after the variable name, and works in the same way as the . after the literal in b"frase_de_Teste".decode().

A related but little known trick is that even methods associated with numbers - both floating point and integers, can be called straight from literals - but in this case at least a blank space is required separating the digits from the numbers, to differentiate access attributes from decimal point - for example: 1234 .to_bytes(2, "little")

0

The method .decode works with variables as well, not only with literals. Run the following code and see:

original = 'Olá, mundo'
encodado = original.encode('utf-8')
decodado = encodado.decode('utf-8') # Funciona perfeitamente!

print(encodado)
print(decodado)
print(original == decodado)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.