How to Get ASCII Value of a Character in Python

Muhammad Waiz Khan Feb 02, 2024
How to Get ASCII Value of a Character in Python

This tutorial will explain the various ways to get an ASCII value of a character in Python. The ASCII character encoding is a standard character encoding for electronic communication. All the regular characters have some ASCII values, used to represent text in a computer and other electronic devices. For instance, the ASCII value of a is 97, and that of A is 65.

Get the ASCII Value of a Character in Python Using the ord() Function

The ord() function takes a character as input and returns the decimal equivalent Unicode value of the character as an integer. We pass the character to the ord() function to get the ASCII value of the ASCII characters. If we pass some non-ASCII character like ß to the ord() function, it will return the Unicode value as ß is not an ASCII character.

The below example code demonstrates how to use the ord() function to get the ASCII value of a character:

print(ord("a"))
print(ord("A"))
print(ord(","))

Output:

97
65
44

We can also get the ASCII value of each character of a string using the for loop, as shown in the example code below:

string = "Hello!"
for ch in string:
    print(ch + " = " + str(ord(ch)))

Output:

H = 72
e = 101
l = 108
l = 108
o = 111
! = 33

Related Article - Python ASCII