AppDividend
Latest Code Tutorials

Python ord Function Example | ord() Function In Python Tutorial

0

Python ord Function | ord() Function In Python Tutorial is today’s topic. The ord() function returns the number representing the Unicode code of a specified character. The ord() method returns the integer representing the Unicode code point for the given Unicode character.

Python ord Function

The ord() function in Python accepts a string of length one as an argument and returns the Unicode code point representation of the passed argument. For example, ord(‘B’) returns 66, which is a Unicode code point value of character ‘B.’ The ord() method is the inverse of the chr() function.

See the following syntax.

ord(c)

The parameter is any character whose length is 1.

See the following example.

# app.py

# code point of integer
print(ord('1'))

# code point of alphabet 
print(ord('E'))
print(ord('K'))

# code point of character
print(ord('$'))
print(ord('#'))
print(ord('~'))

See the output.

➜  pyt python3 app.py
49
69
75
36
35
126
➜  pyt

If the string length is more then one, then the TypeError will be raised.

See the following example of TypeError.

# app.py

print(ord('MK'))

See the output.

➜  pyt python3 app.py
Traceback (most recent call last):
  File "app.py", line 2, in <module>
    print(ord('MK'))
TypeError: ord() expected a character, but string of length 2 found
➜  pyt

So, we got the TypeError. That means we do not need to pass the string of length of 2 or more.

The Unicode code point is given the meaning by Unicode standard, which is a number.

#Code points of numbers 0-10 by using a range

See the following code example.

# app.py

for n in range(10):

    print("Unicode code point of", n, '=', ord(str(n)))

See the output.

➜  pyt python3 app.py
Unicode code point of 0 = 48
Unicode code point of 1 = 49
Unicode code point of 2 = 50
Unicode code point of 3 = 51
Unicode code point of 4 = 52
Unicode code point of 5 = 53
Unicode code point of 6 = 54
Unicode code point of 7 = 55
Unicode code point of 8 = 56
Unicode code point of 9 = 57
➜  pyt

As range items are numbers, so it will produce an error if directly used in the ord() function. As such, ord() takes a string, so the str() function is used for converting the number into the string.

#Dynamic character example

See the following code example.

# app.py

c = input("Enter a character: ")

data = ord(c)


print("The Unicode code point of the character is: ", c, "=", data)

See the output.

➜  pyt python3 app.py
Enter a character: E
The Unicode code point of the character is:  E = 69
➜  pyt

Finally, Python ord() Function Example is over.

Leave A Reply

Your email address will not be published.

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