Open In App

How To Convert Unicode To Integers In Python

Last Updated : 24 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Unicode is a standardized character encoding that assigns a unique number to each character in most of the world's writing systems. In Python, working with Unicode is common, and you may encounter situations where you need to convert Unicode characters to integers. This article will explore five different methods to achieve this in Python.

Convert Unicode To Integers In Python

Below, are the ways to Convert Unicode To Integers In Python.

  • Using ord() Function
  • Using List Comprehension
  • Using int() with base
  • Using map() Function

Convert Unicode To Integers Using ord() Function

The ord() function in Python returns an integer representing the Unicode character. This is a simple method for converting Unicode to integers.

Python3
unicode_char = 'A'
integer_value = ord(unicode_char)
print(f"Unicode '{unicode_char}' converted to integer: {integer_value}")

Output
Unicode 'A' converted to integer: 65

Convert Unicode To Integers Using List Comprehension

This method converts each Unicode character in the string 'World' to integers using list comprehension with the `ord()` function, and the result is stored in the list `integer_list`.

Python3
unicode_string = 'World'
integer_list = [ord(char) for char in unicode_string]
print(f"Unicode '{unicode_string}' converted to integers: {integer_list}")

Output
Unicode 'World' converted to integers: [87, 111, 114, 108, 100]

Convert Unicode To Integers Using map() Function

If you have a string of Unicode characters and want to convert them to a list of integers, you can use the map() function along with ord().

Python3
unicode_string = 'Hello'
integer_list = list(map(ord, unicode_string))
print(f"Unicode '{unicode_string}' converted to integers: {integer_list}")

Output
Unicode 'Hello' converted to integers: [72, 101, 108, 108, 111]

Convert Unicode To Integers Using int() with base

If you have a hexadecimal Unicode representation, you can use the int() function with base 16 to convert it to an integer.

Python3
unicode_hex = '1F60D'
integer_value = int(unicode_hex, 16)
print(f"Unicode 'U+{unicode_hex}' converted to integer: {integer_value}")

Output
Unicode 'U+1F60D' converted to integer: 128525

Conclusion

In conclusion, Python provides multiple methods to seamlessly convert Unicode characters to integers, catering to diverse needs and scenarios. Whether utilizing the straightforward ord() function, employing list comprehension, or manipulating byte representations, Python offers flexibility in handling Unicode conversions.


Next Article
Article Tags :
Practice Tags :

Similar Reads