28

Hi I need to be able to convert a ascii character into its decimal equivalent and vice-versa.

How can I do that?

Alpagut
  • 1,173
  • 5
  • 15
  • 21
  • 2
    possible duplicate of [ASCII value of a character in python](http://stackoverflow.com/questions/227459/ascii-value-of-a-character-in-python) – Adam Matan Dec 08 '10 at 12:06

4 Answers4

58
num=ord(char)
char=chr(num)

For example,

>>> ord('a')
97
>>> chr(98)
'b'

You can read more about the built-in functions in Python here.

Adam Matan
  • 128,757
  • 147
  • 397
  • 562
4

Use ord to convert a character into an integer, and chr for vice-versa.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
2

ord

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
2

You have to use ord() and chr() Built-in Functions of Python. Check the below explanations of those functions from Python Documentation.

ord()

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().

chr()

Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().

So this is the summary from above explanations,

Check this quick example get an idea how this inverse work,

>>> ord('H')
72
>>> chr(72)
'H'
>>> chr(72) == chr(ord('H'))
True
>>> ord('H') == ord(chr(72))
True
Kushan Gunasekera
  • 7,268
  • 6
  • 44
  • 58