Horje
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.

Python3
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’.

Python3
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


Reffered: https://www.geeksforgeeks.org


Python

Related
Python Program to Check If a Number is a Harshad Number Python Program to Check If a Number is a Harshad Number
Python program to check if the given number is Happy Number Python program to check if the given number is Happy Number
Loading Different Data Files in Python Loading Different Data Files in Python
Python Generics Python Generics
How to Print a Tab in Python: Enhancing Text Formatting How to Print a Tab in Python: Enhancing Text Formatting

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15