Sam Goldrick
Sam Goldrick

Reputation: 69

Convert list of numbers to characters

I need to convert a list of numbers to a list of corresponding characters. I have tried using the chr() function e.g:

numlist= [122, 324, 111, 789, 111]
chr(numlist)

The problem I am having is that the chr() function can only take one argument, and cannot convert lists of numbers to lists of letters. How can I do this?

Upvotes: 2

Views: 18263

Answers (3)

anon582847382
anon582847382

Reputation: 20371

You need to iterate over numlist and convert each item, creating a new list:

characters = [chr(n) for n in numlist]   # Use unichr instead in Python 2.
# ['z', 'ń', 'o', '̕', 'o']

Upvotes: 6

Hackaholic
Hackaholic

Reputation: 19743

for chr argument must be in range 0 to 255, as char only handle ASCII ie 8 bit, 2^8 ->256 for greater than 255 one should use unichr in python 2.x

>>> [ unichr(x) for x in numlist ]
[u'z', u'\u0144', u'o', u'\u0315', u'o']

if you apply chr in greater than 255, you will get ValueError

>>> chr(256)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(256)

in python 3x:

[ chr(x) for x in numlist ]
['z', 'ń', 'o', '̕', 'o']

Upvotes: 0

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

Try map function in python3

In [5]: list(map(chr,numlist))
Out[5]: ['z', 'ń', 'o', '̕', 'o']

Upvotes: 2

Related Questions