Como Converter strings em Bytes em Python
-
Construtor de
bytespara converter string em bytes em Python -
Construtor
str.encodepara converter string em bytes em Python
Vamos introduzir métodos de conversão de strings para bytes em Python 3.
- Método construtor
bytes - Método
str.encode
bytes tipo de dados é um tipo incorporado introduzido a partir do Python 3, e bytes em Python 2.x é na verdade o tipo string, portanto não precisamos introduzir esta conversão em Python 2.x.
Construtor de bytes para converter string em bytes em Python
O construtor de classes bytes constrói um array de bytes a partir de dados como string.
bytes(string, encoding)
Nós precisamos especificar o argumento encoding, caso contrário, ele levanta um TypeError.
>>> bytes("Test", encoding = "utf-8")
b'Test'
>>> bytes("Test")
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
bytes("Test")
TypeError: string argument without an encoding
Construtor str.encode para converter string em bytes em Python
str.encode(encoding=)
O método encode da classe string também poderia converter a string em bytes. Ele tem uma vantagem em relação ao método acima, ou seja, você não precisa especificar a encoding se a sua encoding pretendida é utf-8.
>>> test = "Test"
>>> test.encode()
b'Test'
>>> test.encode(encoding="utf-8")
b'Test'
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn FacebookArtigo relacionado - Python Bytes
- Como Converter Bytes para Integers em Python 2.7 e 3.x
- Como Converter Int em Bytes em Python 2 e Python 3
- Converter Int para Binário em Python
- Como Converter Bytes em Strings em Python 2 e Python 3
- B na frente da string em Python
