Skip to content
Advertisement

Python UTF-16 unicode conversion

I’m using the below code to convert Arabic to Unicode UTF-16.

for example I have an Arabic text as مرحبا

JavaScript

this code provide Unicode string as 0x6450x6310x62d0x6280x627

The format in which I need Unicode is u0645u0631u062du0628u0627

I want to replicate this website

using the above method I’m using replace method to convert 0x format to u0 format but 0x format don’t convert special characters as expected so I’ve to use replace method.

JavaScript

Using the default python encoding, UTF-16 didn’t provide encoding in u0 format.

JavaScript

How can I get results in u0 format as this this website is providing in UTF-16 format.

Thanks.

Advertisement

Answer

This problem is just about how you represent the hex value. To get the string in the representation you want, you can use

JavaScript

Short explanation

Consider the first character of the text:

JavaScript

It has integer (decimal) value 1605. This in hex is 645:

JavaScript

You can also use string formatting (for example f-strings in Python 3.6+) to show it as u0645:

JavaScript

The x in the format string means “hex”. The 0>4 means that print it as 4-digit number, and pad it with zeroes.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement