Python’s ord() Function

Learn Python @ Freshers.in

In Python, the ord() function plays a pivotal role in character encoding by converting characters to their ASCII integer values. Let’s delve into its workings to grasp its significance in Python programming.

Understanding ord() Function

The ord() function in Python is used to obtain the ASCII value of a character. Its syntax is straightforward:

ord(c)

Here, c represents the character whose ASCII value you want to retrieve.

Example 1: Basic Usage

char = 'A'
ascii_val = ord(char)
print("ASCII value of", char, "is:", ascii_val)

Output 1:

ASCII value of A is: 65

Example 2: Using in a Loop

word = "Python"
for char in word:
    print("ASCII value of", char, "is:", ord(char))

Output 2:

ASCII value of P is: 80
ASCII value of y is: 121
ASCII value of t is: 116
ASCII value of h is: 104
ASCII value of o is: 111
ASCII value of n is: 110

Example 3: Conversion from Unicode Characters

unicode_char = 'π'
ascii_val = ord(unicode_char)
print("ASCII value of", unicode_char, "is:", ascii_val)

Output 3:

ASCII value of π is: 960

Points to Remember

  • The ord() function returns the ASCII value of a character.
  • It accepts a single character as input and returns its corresponding integer value.
  • ord() is particularly useful for character manipulation, encoding, and decoding tasks in Python.
Author: user