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

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

Susan Sarandon
Release: 2024-11-21 03:16:15
Original
199 people have browsed it

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

Finding the ASCII Value of a Character in Python

Retrieving the numerical representation of a character as its ASCII value is a fundamental task in Python programming. Here's how you can accomplish this:

Getting the ASCII Value

Python provides the ord() function, which returns the integer value corresponding to the given character. For instance:

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

This returns the ASCII value of the lowercase letter 'a', which is 97.

Converting Back to a Character

To convert the ASCII value back to its character representation, you can use the chr() function. For example:

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

Incrementing and Decrementing ASCII Values

Using ord() and chr(), you can perform operations to increment or decrement the ASCII value of a character. For instance:

>>> chr(ord('a') + 3)
'd'
Copy after login

This shifts the character 'a' three positions to the right in the ASCII table, resulting in the letter 'd'.

Unicode Support

Python 2 supported the unichr() function to work with Unicode characters, but in Python 3, chr() can handle Unicode as well.

>>> chr(1234)
'\u04d2'
Copy after login

This returns the Unicode character corresponding to the code point 1234.

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