Skip to content

Commit 3ff590c

Browse files
[Edit] Python Built-In Functions: ord()
* [Edit] Python: built-in-functions: ord() * Update ord.md ---------
1 parent 91a7764 commit 3ff590c

File tree

1 file changed

+152
-18
lines changed
  • content/python/concepts/built-in-functions/terms/ord

1 file changed

+152
-18
lines changed
Lines changed: 152 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,184 @@
11
---
22
Title: 'ord()'
3-
Description: 'Returns the integer that represents the Unicode character argument.'
3+
Description: 'Returns a number representing the unicode point for a specified character.'
44
Subjects:
5+
- 'Code Foundations'
56
- 'Computer Science'
67
Tags:
7-
- 'Functions'
88
- 'Characters'
9+
- 'Functions'
10+
- 'Strings'
911
- 'Unicode'
10-
- 'Integers'
1112
CatalogContent:
1213
- 'learn-python-3'
1314
- 'paths/computer-science'
1415
---
1516

16-
The **`ord()`** function returns the integer that represents the Unicode character argument. It is the inverse function of [`chr()`](https://www.codecademy.com/resources/docs/python/built-in-functions/chr) which provides the Unicode character for the integer passed.
17+
The **`ord()`** function is a built-in Python function that converts a Unicode character to its corresponding integer Unicode code point value. It essentially performs the opposite operation of the [`chr()`](https://www.codecademy.com/resources/docs/python/built-in-functions/chr) function, which converts an integer to its Unicode character.
18+
19+
When working with text processing, character encoding, or data conversion, the `ord()` function serves as an essential tool. It allows programmers to work with the numerical representation of characters, which is helpful for various applications such as encryption algorithms, character manipulation, and data validation.
1720

1821
## Syntax
1922

2023
```pseudo
21-
ord(char)
24+
ord(character)
2225
```
2326

24-
The function takes a character argument `char` and returns the integer value that represents it in Unicode.
27+
**Parameters:**
28+
29+
- `character`: A Unicode character (string of length 1). If the string contains more than one character, a `TypeError` is raised.
2530

26-
## Example
31+
**Return value:**
2732

28-
The example below demonstrates how to provide an argument to `ord()` and print the result.
33+
The `ord()` function returns an integer that represents the Unicode code point for the given character.
34+
35+
## Example 1: Basic Usage of `ord()`
36+
37+
This example demonstrates how to get the Unicode value of basic characters:
2938

3039
```py
31-
print(ord('H'))
40+
# Get Unicode value of uppercase letter
41+
print(ord('A'))
42+
43+
# Get Unicode value of lowercase letter
44+
print(ord('a'))
45+
46+
# Get Unicode value of a digit
47+
print(ord('5'))
48+
49+
# Get Unicode value of a special character
50+
print(ord('@'))
3251
```
3352

34-
This produces the output:
53+
This example results in the following output:
3554

3655
```shell
37-
72
56+
65
57+
97
58+
53
59+
64
3860
```
3961

40-
## Codebyte Example
62+
The ASCII values for 'A', 'a', '5', and '@' are 65, 97, 53, and 64 respectively. These values are part of the Unicode standard which includes ASCII as its first 128 characters.
63+
64+
## Example 2: Working with Non-ASCII Characters
65+
66+
This example shows how `ord()` handles characters beyond the ASCII range, including symbols and characters from different languages:
67+
68+
```py
69+
# Unicode for emoji (smiling face)
70+
print(ord('😀'))
71+
72+
# Unicode for Chinese character (means "center")
73+
print(ord(''))
4174

42-
In the example below, the function `ord()` is used on each character in the string `word`. Each character is printed alongside the integer value that represents it.
75+
# Unicode for Russian character (Cyrillic letter)
76+
print(ord('Я'))
4377

44-
> **Note:** Letters 'C' and 'c' do not return the same integer. This is because uppercase and lowercase letters are represented by different integers in Unicode.
78+
# Unicode for Euro symbol
79+
print(ord(''))
80+
```
81+
82+
This example results in the following output:
4583

46-
```codebyte/python
47-
word = "Codecademy!"
48-
for char in word:
49-
print(char, ord(char))
84+
```shell
85+
128512
86+
20013
87+
1071
88+
8364
5089
```
90+
91+
As shown, the `ord()` function can handle characters from any language or symbol set in the Unicode standard, returning their unique numerical code points.
92+
93+
## Codebyte Example: Character Manipulation with `ord()`
94+
95+
This example demonstrates a practical application of the `ord()` function in a Caesar cipher implementation, which is a basic encryption technique:
96+
97+
```py
98+
def caesar_encrypt(text, shift):
99+
"""
100+
Encrypts a text using the Caesar cipher technique.
101+
102+
Args:
103+
text: The text to encrypt
104+
shift: The number of positions to shift each letter
105+
106+
Returns:
107+
The encrypted text
108+
"""
109+
result = ""
110+
111+
for char in text:
112+
# Check if character is a letter
113+
if char.isalpha():
114+
# Get the Unicode value
115+
char_code = ord(char)
116+
117+
# Determine if it's uppercase or lowercase
118+
base = ord('A') if char.isupper() else ord('a')
119+
120+
# Apply the shift (modulo 26 to wrap around the alphabet)
121+
shifted_code = (char_code - base + shift) % 26 + base
122+
123+
# Convert back to a character
124+
result += chr(shifted_code)
125+
else:
126+
# Keep non-alphabetic characters unchanged
127+
result += char
128+
129+
return result
130+
131+
# Example usage
132+
original_text = "Hello, World!"
133+
shift_value = 3
134+
encrypted_text = caesar_encrypt(original_text, shift_value)
135+
136+
print(f"Original: {original_text}")
137+
print(f"Encrypted (shift {shift_value}): {encrypted_text}")
138+
```
139+
140+
In this example, the `ord()` function converts each character to its Unicode value, apply a shift, and then convert back to a character using the `chr()` function. This demonstrates how `ord()` can be used in practical text transformation scenarios.
141+
142+
## Frequently Asked Questions
143+
144+
### 1. What happens if I pass more than one character to `ord()`?
145+
146+
If you pass a string with more than one character to `ord()`, Python will raise a `TypeError`. The function is designed to work with exactly one character.
147+
148+
```py
149+
try:
150+
print(ord('AB'))
151+
except TypeError as e:
152+
print(f"Error: {e}")
153+
```
154+
155+
The output for this code will be:
156+
157+
```shell
158+
Error: ord() expected a character, but string of length 2 found
159+
```
160+
161+
### 2. What is the relationship between `ord()` and `chr()`?
162+
163+
The `ord()` and `chr()` functions are complementary. `ord()` converts a character to its corresponding Unicode code point, while `chr()` converts a Unicode code point to its character representation.
164+
165+
```py
166+
character = 'A'
167+
code_point = ord(character)
168+
print(f"ord('{character}') = {code_point}")
169+
170+
# Convert back using chr()
171+
same_character = chr(code_point)
172+
print(f"chr({code_point}) = '{same_character}'")
173+
```
174+
175+
The output for this code will be:
176+
177+
```shell
178+
ord('A') = 65
179+
chr(65) = 'A'
180+
```
181+
182+
### 3. Can `ord()` handle characters from any language?
183+
184+
Yes, `ord()` can handle any character that is part of the Unicode standard, which contains characters from virtually all modern written languages, as well as many symbols and emojis.

0 commit comments

Comments
 (0)