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

Susan Sarandon
Release: 2024-11-25 10:32:10
Original
379 people have browsed it

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

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

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!

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