Python Program to Find ASCII Value of a Character
Given a character, we need to find the ASCII value of that character using Python.
ASCII (American Standard Code for Information Interchange) is a character encoding standard that employs numeric codes to denote text characters. Every character has its own ASCII value assigned from 0-127.
Examples:
Input: a
Output: 97
Input: D
Output: 68
Python Program to Find ASCII Value of a Character
Below are some approaches by which we can find the ASCII value of a character in Python:
- Using the ord() function
- Using a dictionary mapping
Using the ord() Function
In this example, the function method1
returns the ASCII value of a given character using the ord()
function in Python. It takes a character as input, converts it to its corresponding ASCII value, and returns it.
def method1(char):
return ord(char)
character = 'a'
print("ASCII value of", character, "is:", method1(character))
Output
ASCII value of a is: 97
Using a Dictionary Mapping
In this example, the function method2
creates a dictionary mapping each character in the input string to its ASCII value, then returns the ASCII value corresponding to the given character. It effectively retrieves the ASCII value of the character 'D'.
def method2(char):
ascii_dict = {c: ord(c) for c in char}
return ascii_dict[char]
character = 'D'
print("ASCII value of", character, "is:", method2(character))
Output
ASCII value of D is: 68