Apa Itu ASCII dalam Python Mitra IT | Your Trusted & Reliable Software Solutions

ASCII Functions in Python: Meaning, How to Use, and Examples

When learning Python, beginners often focus solely on numbers, variables, or branching logic.

However, beneath its simplicity lies a Python concept that determines how the computer understands the characters you write. This concept is called ASCII.

By understanding ASCII functions in Python, you’ll gain a better understanding of how Python reads characters, allowing you to build more robust and structured program logic!

What is ASCII and its Role in Python?

The American Standard Code for Information Interchange, or ASCII, is a numeric code standard used to represent characters.

Each letter, number, and symbol has a specific numerical value that computers can understand.

In Python, ASCII plays a crucial role in character processing, such as text comparison, input validation, and string data manipulation.

ASCII Functions Used in Python

In Python, you don’t need to manually memorize the ASCII table.

Python provides built-in functions that make it easy to work with ASCII codes directly.

1. The ord() Function to Get ASCII Values

The ord() function is used to convert a character to its ASCII value.

When you enter a character into this function, Python will return the number that represents that character.

This function is very useful when you want to compare characters based on their order or value.

2. The chr() Function to Convert ASCII Codes to Characters

The opposite of ord(), the chr() function is used to convert ASCII numbers to characters. Simply input an ASCII value and Python will return the corresponding character.

This function is often used when you want to dynamically generate characters from a specific calculation.

Differences Between the ord() and chr() Functions

To make things easier, here’s a brief table showing the differences between the ord() and chr() functions.

Input Output Functions Main Uses

ord() ASCII Number Character Retrieves the ASCII value of a character

chr() ASCII Number Character Converts an ASCII code to a character

How to Use ASCII Functions in Python

To make it easier to understand, let’s look at how to use ASCII functions directly in Python through a simple example.

How to Use ord() on Letters and Symbols

Here’s a guide on using the ord() function in Python:

1. Determine the Character You Want to Check

First, determine the character whose ASCII value you want to find. This character can be a letter, number, or symbol, for example, ‘A’, ‘a’, or ‘!’.

2. Use the ord() Function on a Character

Basic Usage

The syntax is very simple: ord(character)

Input: A string of exactly 1 character in length.

Output: An integer representing the Unicode code of that character.

Example Code:

Python

# Converting characters to letters

print(ord(‘A’)) # Output: 65

print(ord(‘a’)) # Output: 97

# Converting characters to numbers and symbols

print(ord(‘1’)) # Output: 49

print(ord(‘$’)) # Output: 36

# Converting emojis or special characters

print(ord(‘🚀’)) # Output: 128640

After specifying a character, call the ord() function with that character as a parameter. For example, you could write ord(‘A’) in Python code.

3. Observe the Resulting ASCII Value

1. Primary Character Range

ASCII values ​​are not random. Characters in the same category are usually in sequential numerical order:

Numbers (‘0’ – ‘9’): Have a value range of 48 to 57.

Capital Letters (‘A’ – ‘Z’): Have a value range of 65 to 90.

Lowercase Letters (‘a’ – ‘z’): Have a value range of 97 to

Tuples are written using curly brackets () and each element is separated by a comma.

Difference Between Uppercase and Lowercase LettersOne thing that often traps beginners is the difference between uppercase and lowercase letters. In a computer system, ‘A’ and ‘a’ are different entities. The difference between the same lowercase and uppercase letter is always 32. Example: ord(‘a’) – ord(‘A’) $rightarrow$ $97 – 65 = 32$.

3. Control Characters and Symbols

In addition to letters and numbers, ord() also returns values ​​for invisible characters (whitespace):

Space (‘ ‘): Value 32.

Enter/Newline (‘n’): Value 10.

Quick Reference TableCharactersValues ​​ord()Categories048NumbersA65 Capital Letters a97 Lowercase Letters!33Symbols 32Spaces

Python will return a number that represents the character in ASCII code. For example, the letter ‘A’ has an ASCII value of 65, while the symbol ‘!’ has a value of 33.

4. Utilize ASCII Values ​​for Program Logic

You can directly use these values ​​for various program logic needs, such as comparing characters, validating input, or grouping text data in a specific order.

How to Use chr() on ASCII Numbers

Here are the steps to use the chr() function to convert ASCII numbers to characters:

1. Prepare the ASCII Number to be Converted

First, prepare the ASCII number value you want to convert to a character, for example, the number 97 represents the lowercase letter ‘a’.

2. Use the chr() function on ASCII numbers

Basic Usage

The syntax is: cjr(integer)

Input: A valid integer in the Unicode/ASCII standard.

Output: A character string corresponding to that code.

Code Example:

Python

# Converting numbers to letters

print(chr(65)) # Output: ‘A’

print(chr(97)) # Output: ‘a’

# Converting numbers to symbols

print(chr(35)) # Output: ‘#’

print(chr(128161)) # Output: ‘💡’

Reciprocal Relationship (ord vs chr)These two functions complement each other. If you put the result of one function into the other, you will return to the initial value. Mathematically in programming:$$chr(ord(‘X’)) = ‘X’$$$$ord(chr(120)) = 120$$

Example: Printing the Entire Alphabet

Instead of manually typing ‘A’ through ‘Z’, you can use chr() in a loop to display them automatically:

Python

# Print the letters A through Z

for i in range(65, 91):

print(chr(i), end=” “)

# Output: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

Things to Note

Number Range: You can enter numbers from 0 to 1,114,111 (base 16: 0x10FFFF). If the number is outside this range, Python will throw a ValueError.

Data Type: Ensure the input is an integer. Using a numeric string like chr(“65”) will cause an error.

3. Observe the Character of the Conversion Results

Here are some things to keep in mind when converting:

1. “Invisible” Characters (Control Characters)

If you enter a number between 0 and 31, you may not see anything on the screen (or just a strange box/symbol). These are control characters.

chr(7): Produces a beep on some older terminals (Bell).

chr(9): Produces a Tab.

chr(10): Produces a Line Feed (new line).

2. Unicode Characters and International Symbols

Python fully supports Unicode, allowing you to explore thousands of characters beyond the standard Latin alphabet.

Greek letters: chr(937) produces Ω (Omega).

Mathematical symbols: chr(8734) produces ∞ (Infinity).

Japanese characters: chr(12354) produces あ (Hiragana ‘a’).

Example Experiment: “Looking” at the Contents of a Table

You can create a small program to see what characters are generated from a given range of numbers:

Python

# Observe characters from code 100 to 110

for i in range(100, 111):

print(f”The number {i} produces the character: {chr(i)}”)

Conversion Flow SummaryTo avoid confusion, remember this pattern:Character to Number: Use ord(‘A’) $rightarrow$ The result is 65.Number to Character: Use chr(65) $rightarrow$ The result is ‘A’.Manipulation: You can add numbers (e.g.: $65 + 1$) and then convert them back to characters (chr(66)) to get the next letter (‘B’).

Once executed, Python will display the character corresponding to the ASCII value. In the previous example, the result is the letter ‘a’.

4. Use Characters for Text Processing

You can use these converted characters to build strings, create character patterns, or perform dynamic text manipulation in Python programs.

When Should You Use ASCII Functions in Python?

Although they aren’t used every day, there are several situations where ASCII functions become very relevant in Python programming.

1. Basic Character Processing

ASCII functions are very useful when you need to process characters one by one, such as distinguishing between uppercase and lowercase letters or checking alphabetical order.

2. Learning Encoding Concepts for Beginners

By understanding ASCII, you can more easily understand the concept of encoding and understand how text is stored and processed by computers.

3. Logical Basis for Encryption and Data Validation

In some cases, ASCII is used as a logical basis for simple encryption or data validation. For example, ensuring that input only contains certain letters or numbers.

Examples of Applying ASCII Functions in Python Programs

After understanding the concepts and functions, you also need to see how ASCII is applied in real-world situations.

1. Converting a String to an ASCII Code Sequence

With the ASCII function, you can convert each character in a string to its ASCII value using the ord() function. Python will display a string of numbers that represents the original text.

2. Validating Characters Using ASCII Values

You can use the ASCII function to validate user input to ensure it is either alphabetic or numeric. Simply by checking the ASCII value range, you can determine whether the character is valid or not.

3. Simple Text Data Manipulation with ASCII

Finally, this function is used for simple text manipulation, such as converting characters to ASCII numbers, performing calculations, and then converting them back to character form.

Master ASCII Functions and Strengthen Your Python Logic

That’s the definition, how to use them, and examples of ASCII functions in Python that you can use. By understanding these functions, you understand how characters are represented, processed, and manipulated within a program.

Thanks to our practical, project-based approach, you can work on real projects to earn official certification from Coding Studio.

Let’s start your journey to becoming a Python developer!

Why choose Mitra IT?

•⁠ ⁠Expert Team: We have a team of experienced and creative technology experts.

•⁠ ⁠Comprehensive Solutions: We not only provide technology but also offer full support to ensure your business success.

•⁠ ⁠Focused on Results: We are committed to helping you achieve your business goals.

Don’t miss the opportunity to maximize your business potential!

Contact us now for a free consultation.