Python: How to Convert a String to Character Codes

Updated: June 1, 2023 By: Khue Post a comment

Char codes, or character codes, are numbers that represent graphical characters, such as letters, digits, symbols, and punctuation marks. They allow characters to be stored, transmitted, and manipulated by digital computers. For instance, in the ASCII encoding, the character “A” has the char code 65, and the character “!” has the char code 33.

Converting a string into character codes can be useful in encryption algorithms, text processing, etc. In Python, you can turn a given string into char codes by following the steps below:

  1. iterate over each character in the string using a loop.
  2. Apply the ord() function to each character to get its corresponding character code.
  3. Store the character codes in a list or any other data structure.

Code example:

def convert_to_char_codes(string):
    char_codes = []
    for char in string:
        char_codes.append(ord(char))
    return char_codes


print(convert_to_char_codes("Sling Academy"))

Output:

[83, 108, 105, 110, 103, 32, 65, 99, 97, 100, 101, 109, 121]

Instead of defining a reusable custom function, you can also write the code in the one-line style like this:

text = "Welcome to Sling Academy"

# Convert text to char codes with a single line of code
char_codes = [ord(char) for char in text]

print(char_codes)

Output:

[87, 101, 108, 99, 111, 109, 101, 32, 116, 111, 32, 83, 108, 105, 110, 103, 32, 65, 99, 97, 100, 101, 109, 121]

It is possible to make the code even shorter with the help of the map() method, like this:

text = "There are bad devils and good devils."

# Convert text to char codes
char_codes = [list(map(ord, text))]

print(char_codes)

Output:

[[84, 104, 101, 114, 101, 32, 97, 114, 101, 32, 98, 97, 100, 32, 100, 101, 118, 105, 108, 115, 32, 97, 110, 100, 32, 103, 111, 111, 100, 32, 100, 101, 118, 105, 108, 115, 46]]