How to Get the ASCII Value of a Character in Python?

Sometimes, when working with strings, you will need to get the ASCII value of a character. In this short tutorial, I’ll show you how to do this in Python.

In Python, you can get the ASCII value of a character using the ord() function. This function takes in a character (in quotes) and returns the ASCII value of that character.

For example, if you want to get the ASCII value of the letter “a”, you would type in ord(“a”). Try it out below!

print(ord("a")) # This will give you the output 97.
Code language: Python (python)

You can also use this function on multiple characters. For example, let’s say you want to know the ASCII values for the string “python”.

You would type in ord(“python”) like so:

Code language: Python (python)

However, this will return an error because you can only input one character at a time into the ord() function.

If we want to get the ASCII values for each individual character in “python”, we need to use a for loop.

The code would look like this:

for i in "python": print(ord(i))
Code language: Python (python)

The output would be:

112 #ASCII value for “p”
121 #ASCII value for “y”
116 #ASCII value for “t”
104 #ASCII value for “h”
111 #ASCII value for “o”
110 #ASCII value for “n”

We can also use this function to get the ASCII values for string objects. For instance, let’s take a look at the following example where we take a string input from the user and print out its corresponding ASCII values.

s = input("Please enter a string: ") for char in s: print(ord(char), end =" ")
Code language: PHP (php)

In this article, we have learned about how we can get the ASCII value of characters or string objects in Python using the ord() function.

We have also looked at some examples to better understand how this function works.

I hope you found this article helpful and if you have any questions, please feel free to leave them in the comments section below.

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts