How to Conduct Conversion Between Character and ASCII in Python


Through this example, we can get the methods to realize the conversion between character and ASCII in Python.

2. Functions

  • Ord(): The ord() function is a pairing function of the CHR() function (for 8-bit ASCII strings) or the unichr() function (for Unicode objects). It takes a character (a string of length 1) as an argument and returns the corresponding ASCII code value.
  • Chr(): The Chr () function uses an integer within the range (256) (that is, 0 ~ 255) as a parameter to return a corresponding character.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

# user input characters
c = input("Please enter a character: ")

# User enters ASCII code
a = int(input("Please enter an ASCII code: "))

print(c, " has the corresponding ASCII code of", ord(c))
print(a, " has the corresponding character of", chr(a))

Output:

Please enter a character: s
Please enter an ASCII code: 90
s has the corresponding ASCII code of 115
90 has the corresponding character of Z

Please enter a character: f
Please enter an ASCII code: 78
f has the corresponding ASCII code of 102
78 has the corresponding character of N
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments