Skip to content

Commit 244b3bd

Browse files
Alessio Falciniampcode-com
andcommitted
Add ascii_to_char.py to conversions module (#13569)
Amp-Thread-ID: https://ampcode.com/threads/T-93cf35d5-671a-44bb-9813-2efe37afb6bf Co-authored-by: Amp <amp@ampcode.com>
1 parent e2a78d4 commit 244b3bd

File tree

1 file changed

+169
-0
lines changed

1 file changed

+169
-0
lines changed

conversions/ascii_to_char.py

Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
"""Convert ASCII integer values to their corresponding characters."""
2+
3+
4+
def ascii_to_char(ascii_value: int) -> str:
5+
"""
6+
Convert an ASCII integer value to its corresponding character.
7+
8+
Args:
9+
ascii_value: An integer representing an ASCII value (0-127 for standard ASCII,
10+
0-255 for extended ASCII)
11+
12+
Returns:
13+
str: The character corresponding to the ASCII value
14+
15+
Raises:
16+
TypeError: If ascii_value is not an integer
17+
ValueError: If ascii_value is outside the valid ASCII range (0-255)
18+
19+
Examples:
20+
>>> ascii_to_char(65)
21+
'A'
22+
>>> ascii_to_char(97)
23+
'a'
24+
>>> ascii_to_char(48)
25+
'0'
26+
>>> ascii_to_char(32)
27+
' '
28+
>>> ascii_to_char(72)
29+
'H'
30+
>>> ascii_to_char(33)
31+
'!'
32+
>>> ascii_to_char(126)
33+
'~'
34+
>>> ascii_to_char(0)
35+
'\\x00'
36+
>>> ascii_to_char(255)
37+
'ÿ'
38+
>>> ascii_to_char(-1)
39+
Traceback (most recent call last):
40+
...
41+
ValueError: ASCII value must be between 0 and 255
42+
>>> ascii_to_char(256)
43+
Traceback (most recent call last):
44+
...
45+
ValueError: ASCII value must be between 0 and 255
46+
>>> ascii_to_char("65")
47+
Traceback (most recent call last):
48+
...
49+
TypeError: ASCII value must be an integer
50+
>>> ascii_to_char(65.5)
51+
Traceback (most recent call last):
52+
...
53+
TypeError: ASCII value must be an integer
54+
"""
55+
if not isinstance(ascii_value, int):
56+
raise TypeError("ASCII value must be an integer")
57+
58+
if not 0 <= ascii_value <= 255:
59+
raise ValueError("ASCII value must be between 0 and 255")
60+
61+
return chr(ascii_value)
62+
63+
64+
def string_to_ascii(text: str) -> list[int]:
65+
"""
66+
Convert a string to a list of ASCII values.
67+
68+
Args:
69+
text: A string to convert
70+
71+
Returns:
72+
list[int]: List of ASCII values for each character in the string
73+
74+
Raises:
75+
TypeError: If text is not a string
76+
77+
Examples:
78+
>>> string_to_ascii("Hello")
79+
[72, 101, 108, 108, 111]
80+
>>> string_to_ascii("ABC")
81+
[65, 66, 67]
82+
>>> string_to_ascii("123")
83+
[49, 50, 51]
84+
>>> string_to_ascii("")
85+
[]
86+
>>> string_to_ascii(123)
87+
Traceback (most recent call last):
88+
...
89+
TypeError: Input must be a string
90+
"""
91+
if not isinstance(text, str):
92+
raise TypeError("Input must be a string")
93+
94+
return [ord(char) for char in text]
95+
96+
97+
def ascii_list_to_string(ascii_list: list[int]) -> str:
98+
"""
99+
Convert a list of ASCII values back to a string.
100+
101+
Args:
102+
ascii_list: A list of integers representing ASCII values
103+
104+
Returns:
105+
str: The string formed by converting each ASCII value to its character
106+
107+
Raises:
108+
TypeError: If ascii_list is not a list or contains non-integer values
109+
ValueError: If any ASCII value is outside the valid range (0-255)
110+
111+
Examples:
112+
>>> ascii_list_to_string([72, 101, 108, 108, 111])
113+
'Hello'
114+
>>> ascii_list_to_string([65, 66, 67])
115+
'ABC'
116+
>>> ascii_list_to_string([49, 50, 51])
117+
'123'
118+
>>> ascii_list_to_string([])
119+
''
120+
>>> ascii_list_to_string([65, "66", 67])
121+
Traceback (most recent call last):
122+
...
123+
TypeError: All elements must be integers
124+
>>> ascii_list_to_string([65, 256, 67])
125+
Traceback (most recent call last):
126+
...
127+
ValueError: ASCII value must be between 0 and 255
128+
>>> ascii_list_to_string("not a list")
129+
Traceback (most recent call last):
130+
...
131+
TypeError: Input must be a list
132+
"""
133+
if not isinstance(ascii_list, list):
134+
raise TypeError("Input must be a list")
135+
136+
result = []
137+
for value in ascii_list:
138+
if not isinstance(value, int):
139+
raise TypeError("All elements must be integers")
140+
if not 0 <= value <= 255:
141+
raise ValueError("ASCII value must be between 0 and 255")
142+
result.append(chr(value))
143+
144+
return "".join(result)
145+
146+
147+
if __name__ == "__main__":
148+
import doctest
149+
150+
doctest.testmod()
151+
152+
print("ASCII to Character Converter")
153+
print("Enter an ASCII value (0-255) or 'q' to quit:")
154+
155+
while True:
156+
user_input = input("\nASCII value: ").strip()
157+
158+
if user_input.lower() == "q":
159+
print("Goodbye!")
160+
break
161+
162+
try:
163+
ascii_val = int(user_input)
164+
char = ascii_to_char(ascii_val)
165+
print(f"Character: '{char}'")
166+
except ValueError as e:
167+
print(f"Error: {e}")
168+
except TypeError as e:
169+
print(f"Error: {e}")

0 commit comments

Comments
 (0)