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:




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)))


H = 72
e = 101
l = 108
l = 108
o = 111
! = 33
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.