DEV Community

elkogit
elkogit

Posted on

Python ord and chr

Converting the character into encoded ascii or unicode can be done with ord() and chr(). Ascii is very old computing standard, which gives every latin character a number in the computer.

The ascii table is shown below (you may note non english characters are missing, this is because at the time computing was mostly a US thing)

ascii table

You can convert python text characters into ascii character values.
In the conversion process, you can use the methods ord() and chr()



>>> print(ord('a'))
97
>>> print(chr(97))
a
>>>
>>> # reverse order
>>>
>>> print(str(ord('a')))
97
>>> print(chr(ord('a')))
a
>>>


Enter fullscreen mode Exit fullscreen mode

You can also do this for strings:



>>> s = "hello"
>>> for item in s:
...     print(ord(item))
... 
104
101
108
108
111
>>> 


Enter fullscreen mode Exit fullscreen mode

In practice you'll likely not be using ascii tables so much, as Python is a high level programming language. This was very common during the early days of computing but now rarely is used. However, it's good to know about it.

Top comments (0)