Home  >  Article  >  Backend Development  >  How to Get the ASCII Value of a Character in Python?

How to Get the ASCII Value of a Character in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-25 10:32:10378browse

How to Get the ASCII Value of a Character in Python?

Acquiring ASCII Values in Python

Question: How can I retrieve the ASCII value of a character and store it as an integer in Python?

Answer:

The ord() function provides the ASCII value of a character as an integer. If you wish to revert the conversion, the chr() function can be employed.

For example:

>>> ord('a')
97
>>> chr(97)
'a'
>>> chr(ord('a') + 3)
'd'

In Python 2, the unichr() function was also available for retrieving the Unicode character based on its ordinal value:

>>> unichr(97)
u'a'
>>> unichr(1234)
u'\u04d2'

In Python 3, chr() can be used instead of unichr().

For further reference, you can refer to the following documentation:

  • [ord() - Python 3.6.5rc1 documentation](https://docs.python.org/3/library/functions.html#ord)
  • [ord() - Python 2.7.14 documentation](https://docs.python.org/2/library/functions.html#ord)

The above is the detailed content of How to Get the ASCII Value of a Character in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn