Python is full of useful and powerful functions. One such Python function is "ord()". You can use the ord function to convert a single character to its Unicode code point i.e., integer representation. This function becomes very helpful when you are working with text processing, encoding, and ASCII or Unicode values.
Today at PythonCentral, let us explain how to use the Python ord() function, how you can apply this function in practical use cases, and how it helps you with character encoding. Get. Set. Learn!
What is Python ord() function?
The ord function takes any single character string as input and returns its Unicode integer value. Here is how a typical syntax will look like:
ord(character)
Now, let us convert a few single character inputs. We have commented their respective outputs as well.
print(ord('A')) # Output: 65 print(ord('a')) # Output: 97 print(ord('0')) # Output: 48 print(ord('@')) # Output: 64
What are Unicode and ASCII Values
The Unicode standard assigns unique code points to characters. The first 128 Unicode values correspond to ASCII (American Standard Code for Information Interchange).
Here are some characters and their respective ASCII/Unicode values:
- A: 65
- B: 66
- a: 97
- o: 48
- @: 64
- π: 960
Working with the ord() Function
Now that we are familiar with the basics, let us start working with the ord() function.
How to Find Upper and Lowercase Differences
You would have noticed already, there will be differences in output between uppercase and lowercase letters.
print(ord('A') - ord('a')) # Output: -32 (Difference between uppercase and lowercase letters)
Converting Characters in a String to Unicode Values
Here is how you can convert characters in a string to their Unicode values.
text = "PythonCentral" unicode_values = [ord(char) for char in text] print(unicode_values) # Output: [80, 121, 116, 104, 111, 110,67,101,110,116,114,97,108]
Reversing ord() Using chr()
The chr() function performs the reverse of "ord()", i.e., converting an integer (Unicode code point) back to a character. Here is how you can use chr() function:
print(chr(65)) # Output: 'A' print(chr(97)) # Output: 'a' print(chr(960)) # Output: 'π'
Real-World Applications of ord()
Now we have learnt how to use ord. Let us look at some real-world scenarios where this function will be helpful.
Sorting Strings Based on Unicode Values
Here is how you can sort strings based on their Unicode values:
words = ["apple", "Banana", "cherry"] sorted_words = sorted(words, key=lambda w: ord(w[0])) print(sorted_words) # Output: ['Banana', 'apple', 'cherry']
Detecting Character Type (Alphabet, Digit, Special Character)
When you know their respective Unicode values, it becomes easier to identify if a character is an alphabet, a digit, or a special character. Here is how you can do it.
def char_type(c: str) -> str: if 'A' <= c <= 'Z' or 'a' <= c <= 'z': return "Alphabet" elif '0' <= c <= '9': return "Digit" else: return "Special Character" print(char_type("A")) # Output: Alphabet print(char_type("5")) # Output: Digit print(char_type("@")) # Output: Special Character
Wondering where you can use this? Let us give you a hint: "Your password must contain a special character".
Encrypting and Decrypting Messages (Caesar Cipher Example)
Here is a sample syntax for encrypting and decrypting messages:
def caesar_cipher(text: str, shift: int) -> str: encrypted_text = "".join(chr(ord(char) + shift) if char.isalpha() else char for char in text) return encrypted_text message = "Hello" shifted_message = caesar_cipher(message, 3) print(shifted_message) # Output: 'Khoor'
Wrapping Up
The Python ord() function may seem very simple but it is still the preferred choice in the tech community because it executes in O(1) time complexity, which makes it highly efficient. One limitation of Python ord() is that it works only for single characters, passing a string with multiple characters raises an error.
The "ord()" function is a fundamental tool for handling character encoding, text processing, and cryptography in Python. Understanding how Unicode and ASCII work can help you manipulate text data effectively.
By learning the Python ord() function, you can enhance your ability to work with characters, text transformations, and encoding operations efficiently. Though there is not much, we still encourage you to check out the official documentation for Python ord() function.
Related Articles
- Web Development and Data Encryption: Safeguarding User Information
- How to Monitor WoW Character Stats with Python
- Top Python Libraries for AI Text Rewriting