ord() function in Python

Inbuilt ord() function in Python

Examples:

Input : a
Output : 97

Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example, ord(‘a’) returns the integer 97, ord(‘€’) (Euro sign) returns 8364. This is the inverse of chr() for 8-bit strings and of unichr() for unicode objects. If a unicode argument is given and Python was built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive.

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

The syntax can be ord(“a”) or ord(‘a’), both will give same results.

filter_none

edit
close

play_arrow

link
brightness_4
code

# inbuilt function return an 
# integer representing the Unicode code
value = ord("A")
  
# writing in ' ' gives the same result
value1 = ord('A')
  
# prints the unicode value
print value, value1

chevron_right


Output:

65 65
Exceptions

1. TypeError : Raised when string length is more than 1.

filter_none

edit
close

play_arrow

link
brightness_4
code

# inbuilt function return an 
# integer representing the Unicode code
# demonstrating exception
  
# Raises Exception
value1 = ord('AB')
  
# prints the unicode value
print (value1)

chevron_right


Runtime Error :

Traceback (most recent call last):
  File "/home/f988dfe667cdc9a8e5658464c87ccd18.py", line 6, in 
    value1 = ord('AB')
TypeError: ord() expected a character, but string of length 2 found



My Personal Notes arrow_drop_up

Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : manjeet_04



Article Tags :

4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.