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
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'
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'
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'
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!