Python chr() ord() functions | Python Integer to String Representation

Python-chr-ord
Credit: Canva

Overview

Python chr() ord() are built-in functions of Python. They are used to deal with string-to-integer representation and vice versa. This means that both functions are opposite each other.

What’s Next!

In this Python article, we will discuss Python’s built-in functions, chr() and ord(). From the definition to the example, we will cover each segment and explore using Python chr() and ord() functions.

Table of Contents

What is Python’s chr() function?

Python’s chr() function takes an integer as input and returns a single string character representation of the integer from a Unicode string table. In other words, It returns a single string character stored at the specified integer.

Example:

				
					# Get the character that corresponds to a Unicode code point
unicode_value = 65
char = chr(unicode_value)
print(f"The character for Unicode {unicode_value} is '{char}'")

print(chr(65))  # Output: 'A'
print(chr(122))  # Output: 'z'
print(chr(33))  # Output: '!'
print(chr(32))  # Output: ' '
print(chr(64))  # Output: '@'
print(chr(35))  # Output: '#'
print(chr(945))  # Output: 'α'
				
			

What is Python’s ord() function?

Python’s ord() function takes a single string character as input and returns the integer representation of the string from a Unicode integer table. In other words, It returns the integer stored for the specified single string character.

Example:

				
					# Get the Unicode code point of a character
char = 'A'
unicode_value = ord(char)
print(f"The Unicode code for '{char}' is {unicode_value}")

print(ord('z'))  # Output: 122
print(ord('!'))  # Output: 33
print(ord(' '))  # Output: 32
print(ord('\n'))  # Output: 10
print(ord('@'))  # Output: 64
print(ord('#'))  # Output: 35
print(ord('α'))  # Output: 945
				
			

Conclusion: Python chr() ord()

Python `ord()` and `chr()` functions provide a simple way to convert between characters and their corresponding Unicode or ASCII code points. The `ord()` function takes a single character and returns its integer representation. On the other hand, the `chr()` function does the reverse, taking an integer (Unicode or ASCII code) and returning the corresponding character. 

Together, these functions are powerful tools for managing text and symbols, and they are essential for tasks that involve encoding, decoding, or manipulating individual characters in Python.

Recent Articles