Decode unicode to string python

Convert a Unicode String to a String in Python

In this python tutorial, you will learn how to convert a Unicode string to a string.

Table Of Contents

A Unicode string that is used to represent the characters in a number system. If we want to specify a Unicode string, we have to place the character – “u” in front of the string.

Convert a Unicode string to a string using str()

Here, we will use str() to convert Unicode string to string.

Frequently Asked:

It takes only one parameter.

Where inp_str is a Unicode string.
Example 1:

In this example, we will convert the Unicode string – u”Welcome to thisPointer” to a string using str().

# Consider the unicode string inp_str= u"Welcome to thisPointer" # Convert to string print("Converted String: ",str(inp_str))
Converted String: Welcome to thisPointer

Convert a Unicode string to UTF-8

Here, we will take a Unicode string and encode it to UTF-8 using the encode() method. The UTF-8 converts each character in the Unicode string into 1 to 4 characters. The conversion depends upon the character.

Where inp_str is the Unicode string.

In this example, we will convert the Unicode string – u”Welcome to thisPointer” to UTF-8.

# Consider the unicode string inp_str= u"Welcome to thisPointer" # Convert unicode string to UTF-8 encoding inp_str=inp_str.encode('UTF-8') print("Converted String: ", inp_str)
Converted String: b'Welcome to thisPointer'

From the above string, it takes 1 character to convert from Unicode to UTF-8. Suppose, if you want to revert the Unicode string, then you can use the decode() method.

Example:
In this example, we will convert the Unicode string – u”Welcome to thisPointer” to UTF-8 and again decode it to a unicode string.

# Consider the unicode string inp_str= u"Welcome to thisPointer" # Convert unicode string to UTF-8 encoding inp_str=inp_str.encode('UTF-8') print("Converted String: ", inp_str) # Convert back inp_str=inp_str.decode('UTF-8') print("Actual String: ", inp_str)
Converted String: b'Welcome to thisPointer' Actual String: Welcome to thisPointer

Convert a Unicode string to UTF-16

Here, we will take a Unicode string and encode to UTF-16 using encode() method. The UTF-16 converts each character in the Unicode string into mostly 2 bytes.

Where inp_str is the Unicode string.
Example:

In this example, we will convert the Unicode string – u”Welcome to thisPointer” to UTF-16.

# Consider the unicode string inp_str= u"Welcome to thisPointer" # Convert unicode string to UTF-16 encoding inp_str=inp_str.encode('UTF-16') print("Converted String: ", inp_str)
Converted String: b'\xff\xfeW\x00e\x00l\x00c\x00o\x00m\x00e\x00 \x00t\x00o\x00 \x00t\x00h\x00i\x00s\x00P\x00o\x00i\x00n\x00t\x00e\x00r\x00'

From the above string, it returned 2 bytes of each character, if you want to revert the Unicode string, then you can use the decode() method.

In this example, we will convert the Unicode string – u”Welcome to thisPointer” to UTF-16 and again decode it to a Unicode string.

# Consider the unicode string inp_str= u"Welcome to thisPointer" # Convert unicode string to UTF-16 encoding inp_str=inp_str.encode('UTF-16') print("Converted String: ", inp_str) # Convert back inp_str=inp_str.decode('UTF-16') print("Actual String: ", inp_str)
Converted String: b'\xff\xfeW\x00e\x00l\x00c\x00o\x00m\x00e\x00 \x00t\x00o\x00 \x00t\x00h\x00i\x00s\x00P\x00o\x00i\x00n\x00t\x00e\x00r\x00' Actual String: Welcome to thisPointer

Convert a Unicode string to UTF-32

Here, we will take a Unicode string and encode it to UTF-32 using encode() method.UTF-16 converts each character in the Unicode string into mostly 4 bytes.

Where inp_str is the Unicode string.

In this example, we will convert the Unicode string – u”Welcome to thisPointer” to UTF-32.

# Consider the unicode string inp_str= u"Welcome to thisPointer" # Convert unicode string to UTF-32 encoding inp_str=inp_str.encode('UTF-32') print("Converted String: ", inp_str)
Converted String: b'\xff\xfe\x00\x00W\x00\x00\x00e\x00\x00\x00l\x00\x00\x00c\x00\x00\x00o\x00\x00\x00m\x00\x00\x00e\x00\x00\x00 \x00\x00\x00t\x00\x00\x00o\x00\x00\x00 \x00\x00\x00t\x00\x00\x00h\x00\x00\x00i\x00\x00\x00s\x00\x00\x00P\x00\x00\x00o\x00\x00\x00i\x00\x00\x00n\x00\x00\x00t\x00\x00\x00e\x00\x00\x00r\x00\x00\x00'

From the above string, it returned 4 bytes of each character, if you want to revert the Unicode string, then you can use the decode() method.

In this example, we will convert the Unicode string – u”Welcome to thisPointer” to UTF-32 and again decode it to a Unicode string.

# Consider the unicode string inp_str= u"Welcome to thisPointer" # Convert unicode string to UTF-32 encoding inp_str=inp_str.encode('UTF-32') print("Converted String: ", inp_str) # Convert back inp_str=inp_str.decode('UTF-32') print("Actual String: ", inp_str)
Converted String: b'\xff\xfe\x00\x00W\x00\x00\x00e\x00\x00\x00l\x00\x00\x00c\x00\x00\x00o\x00\x00\x00m\x00\x00\x00e\x00\x00\x00 \x00\x00\x00t\x00\x00\x00o\x00\x00\x00 \x00\x00\x00t\x00\x00\x00h\x00\x00\x00i\x00\x00\x00s\x00\x00\x00P\x00\x00\x00o\x00\x00\x00i\x00\x00\x00n\x00\x00\x00t\x00\x00\x00e\x00\x00\x00r\x00\x00\x00' Actual String: Welcome to thisPointer

Summary

In this Python String article, we have seen how to convert a Unicode string to a string using the str(). Also, we saw how to encode the strings to UTF-8, UTF-16, and UTF-32 with encode() and decode the strings to Unicode strings with decode() method. Happy Learning.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Функции 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 . Это означает, что строка преобразуется в поток байтов.

На самом деле это представляется только как исходная строка для удобства чтения с префиксом 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.

Источник

Читайте также:  Adding classes to classpath java
Оцените статью