Home > Backend Development > Python Tutorial > 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
Release: 2024-11-17 06:18:03
Original
988 people have browsed it

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
Copy after login

chr() Function:

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

>>> chr(97)
'a'
Copy after login

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'
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template