How to Get the ASCII Value of a Character in Python
We can use the
chr() functions in Python to convert between characters and their numeric values, which depends on the encoding it’s in.
Assuming we’re using strings in Python 3, these functions will convert over the unicode encoding.
ord() will give us the integer value of a character.
ord('A') # 65 ord('B') # 66
chr() will give us the character representation of a number.
chr(65) # 'A' chr(66) # 'B'
Suppose we want
'A' = 1, 'B' = 2,..., 'Z' = 26.
We can get the numeric value of an uppercase letter like so:
def convert(char): return ord(char) - ord('A') + 1 convert('A') # 1 convert('Z') # 26
Suppose we want the
ith letter of the lowercase alphabet.
def alphabet(offset) return chr(ord('a') + offset) alphabet(3) # 'd' alphabet(5) # 'f'
More Python Articles
- How to Start an HTTP Server in Python
- How to Get All Keys with the Highest Value in Python
- How to Check if a Tuple Exists in a List in Python
- How to Sort a List of Dictionaries By Field in Python
- How to Sort a Dictionary by Value in Python
- How to Flatten a 2D List in Python
- How to Sort a List of Tuples Based on Multiple Elements
- How to Remove Duplicates from a List in Python
- How to Set Multiple Values of a List in Python
- How to Remove the Last N Elements of a List in Python
- How to Loop Over a String in Reverse in Python
- How to Create a Two Dimensional List in Python
- How to Migrate Data from MongoDB to Elasticsearch in Python
- How to Add Key-Value to Dictionary During List Comprehension in Python
- How to Fix "datetime is not JSON serializable" TypeError in Python
- How to Remove a Key From a Dictionary in Python
- Encoding and Decoding Bytes Explained
- How to Paginate/Scroll Elasticsearch Data using Python
- How to Print Without Newline in Python 3
- How to Get the Key with the Maximum Value in Python
- List Comprehension in Python Explained Visually
- How to Check if a String Contains Another String in Python
- What is Enumerate in Python?
- What is the Difference Between List and Tuple in Python?