diff --git a/conversions/ascii_to_char.py b/conversions/ascii_to_char.py new file mode 100644 index 000000000000..db8eaceae3ee --- /dev/null +++ b/conversions/ascii_to_char.py @@ -0,0 +1,49 @@ +""" +Convert an ASCII integer (0-255) to its corresponding character. + +Example: + >>> ascii_to_char(65) + 'A' + >>> ascii_to_char(97) + 'a' + >>> ascii_to_char(36) + '$' + >>> ascii_to_char(300) + Traceback (most recent call last): + ... + ValueError: ASCII value must be in the range 0-255. + +Reference: + https://en.wikipedia.org/wiki/ASCII +""" + + +def ascii_to_char(ascii_value: int) -> str: + """ + Convert an ASCII integer (0-255) into its corresponding character. + + Args: + ascii_value (int): Integer representing an ASCII code (0-255). + + Returns: + str: The corresponding character. + + Raises: + ValueError: If the input is not within 0-255 inclusive. + + >>> ascii_to_char(65) + 'A' + >>> ascii_to_char(97) + 'a' + >>> ascii_to_char(36) + '$' + >>> ascii_to_char(300) + Traceback (most recent call last): + ... + ValueError: ASCII value must be in the range 0-255. + """ + if not isinstance(ascii_value, int): + raise TypeError("Input must be an integer.") + if not 0 <= ascii_value <= 255: + raise ValueError("ASCII value must be in the range 0-255.") + return chr(ascii_value) diff --git a/conversions/char_to_ascii.py b/conversions/char_to_ascii.py new file mode 100644 index 000000000000..b17542da6300 --- /dev/null +++ b/conversions/char_to_ascii.py @@ -0,0 +1,49 @@ +""" +Convert a single character to its ASCII integer value. + +Example: + >>> char_to_ascii('A') + 65 + >>> char_to_ascii('a') + 97 + >>> char_to_ascii('$') + 36 + >>> char_to_ascii('AB') + Traceback (most recent call last): + ... + ValueError: Input must be a single character + +References: + https://en.wikipedia.org/wiki/ASCII +""" + + +def char_to_ascii(char: str) -> int: + """ + Convert a single character to its ASCII integer value. + + Args: + char (str): A single character string. + + Returns: + int: ASCII integer value corresponding to the character. + + Raises: + ValueError: If input is not a single character. + + >>> char_to_ascii('A') + 65 + >>> char_to_ascii('a') + 97 + >>> char_to_ascii('$') + 36 + >>> char_to_ascii('') + Traceback (most recent call last): + ... + ValueError: Input must be a single character + """ + if not isinstance(char, str): + raise TypeError("Input must be a string.") + if len(char) != 1: + raise ValueError("Input must be a single character") + return ord(char)