In this tutorial, I’ll show you how to retrieve ASCII codes from characters and vice versa using Python’s `ord` and `chr` functions. These skills will enhance your understanding of character encoding and data manipulation.
1. Video.
2. Python Source Code.
''' In Python, you can use the ord() function to get the ASCII code of a character and the chr() function to get the character represented by an ASCII code. Here's how you can use these functions: ''' ''' Getting the ASCII Code of a Character To get the ASCII code of a character, use the ord() function: ''' def get_ascii_code_of_a_character(): char = 'A' ascii_code = ord(char) print(ascii_code) # Output: 65 ''' Getting the Character from an ASCII Code To get the character represented by an ASCII code, use the chr() function: ''' def get_character_from_an_ascii_code(): ascii_code = 85 char = chr(ascii_code) print(char) def get_string_character_ascii_code(): string = "Hello" # use list comprehension to get all the character's ascii code in a string. ascii_codes = [ord(char) for char in string] print(ascii_codes) # Output: [72, 101, 108, 108, 111] ''' go to url https://www.ascii-code.com/ to get all ascii code. The first 32 characters in the ASCII-table are unprintable control codes and are used to control peripherals such as printers. ''' def get_all_ascii_code_and_mapped_characters(): # Iterate through ASCII codes from 0 to 127 and print each code and its corresponding character for code in range(128): character = chr(code) print(f"ASCII Code: {code} Character: {character}") if __name__ == "__main__": #get_ascii_code_of_a_character() #get_character_from_an_ascii_code() #get_string_character_ascii_code() get_all_ascii_code_and_mapped_characters()