3

Python ord(): A Step-By-Step Guide

 2 years ago
source link: https://dev.to/itsmycode/python-ord-a-step-by-step-guide-7a9
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

ItsMyCode |

In Python ord() function accepts a single unit of character and returns the equivalent Unicode of the passed argument. In other words, the ord() function can take a string or character of length one and returns an integer representing the Unicode of that string or character.

ord() Function in Python

The ord()function is nothing but the inverse of the Python chr()function. In the chr() function, we will convert the Unicode integer to the character, and in the ord(), it will be the exact opposite in the ord ().

Syntax – ord(ch)

Parameters : ** ** Accepts Unicode character or string of length 1.

Return Value : Returns an integer representing the Unicode character

*Example ord() vs chr() *

print(chr(97))
print(ord('a'))
Enter fullscreen modeExit fullscreen mode

Output

a
97
Enter fullscreen modeExit fullscreen mode

As you can see, the chr(97) returns character ‘a’ , and the inverse*ord('a')returns the integer **97*

ord() Function Examples

Let’s take a look at different types of example.

print('Unicode of lower case alphabet a is ', ord('a')) # lower case alphabet 
print('Unicode of bumber 5 is ', ord('5')) # Number
print('Unicode of symobol $ is ', ord('$')) # dollar
print('Unicode of upper case alphabet A is ', ord('A')) # Upper case alphabet
print('Unicode of zero is ', ord('0')) # Number Zero

Enter fullscreen modeExit fullscreen mode

Output

Unicode of lower case alphabet a is 97
Unicode of bumber 5 is 53
Unicode of symobol $ is 36
Unicode of upper case alphabet A is 65
Unicode of zero is 48
Enter fullscreen modeExit fullscreen mode

TypeError: ord() expected a character, but string of length 2 found.

If the argument passed to the ord() function is more than 1 character, then Python will raise a TypeError: ord()expected a character, but string of length 2 found.

print(ord('AB'))
Enter fullscreen modeExit fullscreen mode

Output

Traceback (most recent call last):
  File "c:\Projects\Tryouts\main.py", line 9, in <module>
    print(ord('AB'))
TypeError: ord() expected a character, but string of length 2 found
Enter fullscreen modeExit fullscreen mode

The post Python ord(): A Step-By-Step Guide appeared first on ItsMyCode.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK