2

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?

nbrooks
  • 18,126
  • 5
  • 54
  • 66
Sam Goldrick
  • 69
  • 1
  • 2
  • 5
  • You have to be clear on what you want - Do you want string version of the numbers you have i.e. 122 will be '122' or Do you want ASCII/UNICODE characters for the decimal numbers you have? – ha9u63a7 Nov 09 '14 at 12:12
  • May be similar to this - http://stackoverflow.com/questions/227459/ascii-value-of-a-character-in-python ? It shows both ASCII and UNICODE versions of conversion. – ha9u63a7 Nov 09 '14 at 12:15
  • Sorry, yes I was looking for ASCII or UNICODE characters, I think I have my answer now, thanks – Sam Goldrick Nov 09 '14 at 12:32

3 Answers3

6

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']
anon582847382
  • 19,907
  • 5
  • 54
  • 57
2

Try map function in python3

In [5]: list(map(chr,numlist))
Out[5]: ['z', 'ń', 'o', '̕', 'o']
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
0

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']
Hackaholic
  • 19,069
  • 5
  • 54
  • 72