Home  >  Article  >  Backend Development  >  How do I get the ASCII value of a character in Python?

How do I get the ASCII value of a character in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-11-17 06:18:03923browse

How do I get the ASCII value of a character in Python?

How to Obtain the ASCII Numeric Value of a Character in Python

Determining the ASCII value of a character as an integer in Python is a straightforward process. Python offers two indispensable functions for this purpose:

ord() Function:

The ord() function retrieves the integer representing the ASCII value of a given character. For instance:

>>> ord('a')
97

chr() Function:

Conversely, the chr() function performs the reverse operation by converting an integer to its corresponding character.

>>> chr(97)
'a'

Examples:

These functions enable various character manipulations. For example, to increment the letter 'a' by three in the ASCII sequence:

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

Python 2 to Python 3 Transition:

In Python 2, the unichr function was also available, which returned Unicode characters corresponding to specified ordinal values. However, in Python 3, chr can be used for both ASCII and Unicode characters.

Documentation References:

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

The above is the detailed content of How do I 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