Python byte string to utf

Функции encode() и decode() в Python

Методы encode и decode Python используются для кодирования и декодирования входной строки с использованием заданной кодировки. Давайте подробно рассмотрим эти две функции.

encode заданной строки

Мы используем метод encode() для входной строки, который есть у каждого строкового объекта.

input_string.encode(encoding, errors)

Это кодирует input_string с использованием encoding , где errors определяют поведение, которому надо следовать, если по какой-либо случайности кодирование строки не выполняется.

encode() приведет к последовательности bytes .

inp_string = 'Hello' bytes_encoded = inp_string.encode() print(type(bytes_encoded))

Как и ожидалось, в результате получается объект :

Тип кодирования, которому надо следовать, отображается параметром encoding . Существуют различные типы схем кодирования символов, из которых в Python по умолчанию используется схема UTF-8.

Рассмотрим параметр encoding на примере.

a = 'This is a simple sentence.' print('Original string:', a) # Decodes to utf-8 by default a_utf = a.encode() print('Encoded string:', a_utf)
Original string: This is a simple sentence. Encoded string: b'This is a simple sentence.'

Как вы можете заметить, мы закодировали входную строку в формате UTF-8. Хотя особой разницы нет, вы можете заметить, что строка имеет префикс b . Это означает, что строка преобразуется в поток байтов.

Читайте также:  Connect python to website

На самом деле это представляется только как исходная строка для удобства чтения с префиксом b , чтобы обозначить, что это не строка, а последовательность байтов.

Обработка ошибок

Существуют различные типы errors , некоторые из которых указаны ниже:

Тип ошибки Поведение
strict Поведение по умолчанию, которое вызывает UnicodeDecodeError при сбое.
ignore Игнорирует некодируемый Unicode из результата.
replace Заменяет все некодируемые символы Юникода вопросительным знаком (?)
backslashreplace Вставляет escape-последовательность обратной косой черты (\ uNNNN) вместо некодируемых символов Юникода.

Давайте посмотрим на приведенные выше концепции на простом примере. Мы рассмотрим входную строку, в которой не все символы кодируются (например, ö ),

a = 'This is a bit möre cömplex sentence.' print('Original string:', a) print('Encoding with errors=ignore:', a.encode(encoding='ascii', errors='ignore')) print('Encoding with errors=replace:', a.encode(encoding='ascii', errors='replace'))
Original string: This is a möre cömplex sentence. Encoding with errors=ignore: b'This is a bit mre cmplex sentence.' Encoding with errors=replace: b'This is a bit m?re c?mplex sentence.'

Декодирование потока байтов

Подобно кодированию строки, мы можем декодировать поток байтов в строковый объект, используя функцию decode() .

encoded = input_string.encode() # Using decode() decoded = encoded.decode(decoding, errors)

Поскольку encode() преобразует строку в байты, decode() просто делает обратное.

byte_seq = b'Hello' decoded_string = byte_seq.decode() print(type(decoded_string)) print(decoded_string)

Это показывает, что decode() преобразует байты в строку Python.

Подобно параметрам encode() , параметр decoding определяет тип кодирования, из которого декодируется последовательность байтов. Параметр errors обозначает поведение в случае сбоя декодирования, который имеет те же значения, что и у encode() .

Важность кодировки

Поскольку кодирование и декодирование входной строки зависит от формата, мы должны быть осторожны при этих операциях. Если мы используем неправильный формат, это приведет к неправильному выводу и может вызвать ошибки.

Первое декодирование неверно, так как оно пытается декодировать входную строку, которая закодирована в формате UTF-8. Второй правильный, поскольку форматы кодирования и декодирования совпадают.

a = 'This is a bit möre cömplex sentence.' print('Original string:', a) # Encoding in UTF-8 encoded_bytes = a.encode('utf-8', 'replace') # Trying to decode via ASCII, which is incorrect decoded_incorrect = encoded_bytes.decode('ascii', 'replace') decoded_correct = encoded_bytes.decode('utf-8', 'replace') print('Incorrectly Decoded string:', decoded_incorrect) print('Correctly Decoded string:', decoded_correct)
Original string: This is a bit möre cömplex sentence. Incorrectly Decoded string: This is a bit m��re c��mplex sentence. Correctly Decoded string: This is a bit möre cömplex sentence.

Источник

Конвертация между байтами и строками#

Избежать работы с байтами нельзя. Например, при работе с сетью или файловой системой, чаще всего, результат возвращается в байтах.

Соответственно, надо знать, как выполнять преобразование байтов в строку и наоборот. Для этого и нужна кодировка.

Кодировку можно представлять как ключ шифрования, который указывает:

  • как «зашифровать» строку в байты (str -> bytes). Используется метод encode (похож на encrypt)
  • как «расшифровать» байты в строку (bytes -> str). Используется метод decode (похож на decrypt)

Эта аналогия позволяет понять, что преобразования строка-байты и байты-строка должны использовать одинаковую кодировку.

encode, decode#

Для преобразования строки в байты используется метод encode:

In [1]: hi = 'привет' In [2]: hi.encode('utf-8') Out[2]: b'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82' In [3]: hi_bytes = hi.encode('utf-8') 

Чтобы получить строку из байт, используется метод decode:

In [4]: hi_bytes Out[4]: b'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82' In [5]: hi_bytes.decode('utf-8') Out[5]: 'привет' 

str.encode, bytes.decode#

Метод encode есть также в классе str (как и другие методы работы со строками):

In [6]: hi Out[6]: 'привет' In [7]: str.encode(hi, encoding='utf-8') Out[7]: b'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82' 

А метод decode есть у класса bytes (как и другие методы):

In [8]: hi_bytes Out[8]: b'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82' In [9]: bytes.decode(hi_bytes, encoding='utf-8') Out[9]: 'привет' 

В этих методах кодировка может указываться как ключевой аргумент (примеры выше) или как позиционный:

In [10]: hi_bytes Out[10]: b'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82' In [11]: bytes.decode(hi_bytes, 'utf-8') Out[11]: 'привет' 

Как работать с Юникодом и байтами#

Есть очень простое правило, придерживаясь которого, можно избежать, как минимум, части проблем. Оно называется «Юникод-сэндвич»:

  • байты, которые программа считывает, надо как можно раньше преобразовать в Юникод (строку)
  • внутри программы работать с Юникод
  • Юникод надо преобразовать в байты как можно позже, перед передачей

Источник

Python Convert Bytes to String

You can convert bytes to strings very easily in Python by using the decode() or str() function. Bytes and strings are two data types and they play a crucial role in many applications. However, in some cases, we may need to convert a byte string to a regular string. In this article, we will learn different methods to convert bytes to a string in Python.

The quick answer to convert bytes to a string in python is to use the decode() or str() function. But there is details to that which we will cover in this article. So let’s get started.

1. Quick Examples of Converting Bytes to String

Below are the most common methods for converting bytes to a string. In the following sections, we will discuss each of these methods in detail with examples.

 # Quick examples of converting bytes to string # Create byte b = b'sparkByExamples' # Using the decode() method s = b.decode('utf-8') # Using the str() constructor s = str(b) # Using the bytes.decode() method s = bytes.decode(b, 'utf-8') # Using the bytearray.decode() method s = b.decode('utf-8') # Using the codecs.decode() method import codecs string = codecs.decode(b, 'utf-8') 

2. What are Bytes in Python?

In Python, bytes is a built-in data type that represents a sequence of bytes. A sequence of bytes can represent any kind of data, including text, images, video, and other types of binary data.

Bytes can represent non-ASCII characters, such as emoji. Because emoji and other non-ASCII characters are represented using multiple bytes, they can be difficult to work with when using regular strings.

 # Byte string with an emoji character a byte_string = b'sparkbyexamples \xF0\x9F\x92\x93' # Print the byte string print(byte_string) # Decode the byte string to a regular string string = byte_string.decode('utf-8') # Print the regular string print(string) 

Yields, the following output:

 # Output: b'sparkbyexamples \xf0\x9f\x92\x93' sparkbyexamples 💓 (love emoji) 

3. Convert Bytes to String using decode()

To convert bytes to strings in python, use the decode() function. decode() is built-in python method used to convert bytes to strings. To use the decode() method, you need to specify the character encoding that was used to encode the byte string.

This method is designed specifically to decode byte strings into regular strings and takes into account the character encoding used to encode the byte string.

 # Create a byte string using utf-8 encoding byte_string = b'sparkbyexamples' # Use utf-8 to decode() the string string = byte_string.decode('utf-8') # Print the regular string print(string) # Output: # sparkbyexamples 

Below is another example that uses UTF-16 encoding:

 # Create a byte string using utf-16 encoding byte_string = b'\xff\xfes\x00p\x00a\x00r\x00k\x00b\x00y\x00e\x00x\x00a\x00m\x00p\x00l\x00e\x00s\x00' # Decode the byte string to a regular string string = byte_string.decode('utf-16') # Print the regular string print(string) # Output: # sparkbyexaples 

Steps to convert bytes to a string using the decode() function in Python:

  1. Find the bytes that you want to convert
  2. Call the decode() method on the byte string and pass the appropriate encoding as an argument.
  3. Assign the decoded string to a variable.
  4. Use the decoded string in your Python code as needed.

You can convert that string back to bytes with UTF-16 encoding using the encode() method:

 # Define a string string = 'sparksbyexamples' # Encode the string to bytes in UTF-16 byte_string = string.encode('utf-16') # Print the byte string print(byte_string) 

4. str() – Bytes to String in Python

str() is a built-in Python function that can be used to convert a bytes object to a string object, by passing the bytes object as the first argument and the desired encoding as the second argument.

Syntax of str() for bytes to string conversion:

 # Syntax of str() str(byte_string, 'utf-8') 

Converting bytes with UTF-8 encoding using the str() function:

 # Create a byte string with a non-ASCII character byte_string = b'sparkbyexamples is \xf0\x9f\x92\x93' # Convert byte string to string using UTF-8 encoding string_utf8 = str(byte_string, 'utf-8') print(string_utf8) # Output: # sparkbyexamples is 💓 (love emoji) 

Byte with a smile emoji using UTF-16 encoding to a string:

 # smile emoji - UTF-16 encoding byte_string = b'\xff\xfe(\x00?\x00?\x00)\x00' # Convert byte string to string string_utf16 = byte_string.decode('utf-16') print(string_utf16) # Output: # 😊 (smile emoji) 

5. Convert Bytes Array to String

To convert a byte array to a string, you can use the bytes() constructor to create a bytes object from the array, and then use the decode() method to convert the bytes object to a string.

 # Create a byte array byte_array = bytearray([115, 112, 97, 114, 107]) # Convert byte array to string using the UTF-8 encoding string_utf8 = bytes(byte_array).decode('utf-8') # Print the string print(string_utf8) # Output: # spark 

6. decode() vs str() for Byte Conversion

The decode() method is used to convert a bytes object to a string by decoding it with a specified character encoding. While the str() constructor is a simpler method that can be used to create a string object directly from a bytes object.

Below is the table, showing the major differences between the decode() and str() for conversion of bytes to string:

Источник

Оцените статью