Convert String List to ASCII Values – Python
We need to convert each character into its corresponding ASCII value. For example, consider the list [“Hi”, “Bye”]. We want to convert it into [[72, 105], [66, 121, 101]], where each character is replaced by its ASCII value. Let’s discuss multiple ways to achieve this.
Using List Comprehension with ord()
A simple and efficient way to convert strings to ASCII values is by using list comprehension along with the ord() function.
a = ["Hi", "Bye"]
b = [[ord(c) for c in s] for s in a]
print(b)
Explanation:
- The ord() function returns the ASCII value of a character.
- We use a nested list comprehension to iterate through each string and convert its characters.
- This method is concise and runs efficiently.
Let’s explore some more ways of converting string list to ascii values in Python.
Table of Content
Using map() with ord()
Another efficient approach is using the map() function, which applies ord() to each character in a string.
a = ["Hi", "Bye"]
b = [list(map(ord, s)) for s in a]
print(b)
Explanation:
- The map() function applies ord() to each character in the string.
- Since map() returns a map object, we convert it into a list.
- This method is similar in efficiency to list comprehension but can be slightly more readable for some.
Using itertools.chain with map()
If we need a flat list of ASCII values instead of a nested list, we can use itertools.chain().
from itertools import chain
a = ["Hi", "Bye"]
b = list(map(ord, chain(*a)))
print(b)
Explanation:
- chain(*a) flattens the list, treating all characters as a single sequence.
- map(ord, …) applies ord() to each character.
- This method is useful when we want a flat list instead of a list of lists.
Using Dictionary Comprehension
If we want to keep track of original characters, we can store them in a dictionary.
a = ["Hi", "Bye"]
b = [{c: ord(c) for c in s} for s in a]
print(b)
Explanation:
- Instead of just converting characters, this stores them as {char: ASCII} pairs.
- This method helps when we need both original characters and their ASCII values.
Using for Loop
We can use a standard for loop to iterate through each character in the list and convert it to ASCII values.
a = ["Hi", "Bye"]
b = []
for s in a:
temp = []
for c in s:
temp.append(ord(c))
b.append(temp)
print(b)
Explanation:
- We initialize an empty list b to store the converted values.
- We loop through each string in the list and convert each character to ASCII using ord().