HOWTO · Python
Come convertire una stringa in byte in Python
Questo tutorial introduce due metodi di come convertire in stringa in byte in Python, il metodo costruttore di byte e il metodo str.encode.
In questa pagina
Introdurremo i metodi per convertire stringhe in byte in Python 3.
- Metodo del costruttore
bytes - Metodo
str.encode
tipo di dati bytes data type è un tipo integrato introdotto da Python 3, e bytes in Python 2.x è in realtà il tipo string, quindi non abbiamo bisogno di introdurre questa conversione in Python 2.x.
Costruttore bytes per convertire la stringa in byte in Python
Il costruttore della classe bytes costruisce un array di byte a partire da dati come le stringhe.
bytes(string, encoding)
Dobbiamo specificare l’argomento encoding, altrimenti solleva un 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
Costruttore str.encode per convertire una stringa in byte in Python
str.encode(encoding=)
Il metodo encode della classe string potrebbe anche convertire la stringa in byte. Ha un vantaggio rispetto al metodo di cui sopra, cioè non è necessario specificare la codifica se la coding prevista è utf-8.
>>> test = "Test"
>>> test.encode()
b'Test'
>>> test.encode(encoding="utf-8")
b'Test'