What is the difference between string and byte string in Python?

Python Methods and Functions

String &it is a sequence of characters; it is an abstract concept and cannot be saved directly to disk. Byte string &it is a sequence of bytes &things that can be stored on disk. 

The mapping between them is the encoding &there are quite a lot of them (and infinitely many are possible) &and you need to know what is applicable in a particular case to perform the conversion, since different encoding may map the same bytes to a different string.



For example, the same byte string in Python can represent 2 different strings in 2 different encodings.






For example

 
 & gt; & gt; & gt; b'xcfx84oxcfx81xcexbdoxcfx82'.decode ('utf-16')'蓏콯캁澽 苏'& gt; & gt; & gt; b'xcfx84oxcfx81xcexbdoxcfx82'.decode ('utf-8')' τoρνoς' 

When you know which encoding to use, you can use the .decode () method of a byte string to get the correct character string out of it. The .encode () method of a character string goes the opposite way and encodes a character string as a byte string.







Tutorials