Alpagut
Alpagut

Reputation: 1173

Python:Ascii character<->decimal representation conversion

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

How can I do that?

Upvotes: 28

Views: 102484

Answers (4)

Kushan Gunasekera
Kushan Gunasekera

Reputation: 8566

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

Upvotes: 2

Karl Knechtel
Karl Knechtel

Reputation: 61526

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

Upvotes: 4

Adam Matan
Adam Matan

Reputation: 136221

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.

Upvotes: 58

SilentGhost
SilentGhost

Reputation: 319611

ord

Upvotes: 2

Related Questions