Search code examples
pythonasciicode-snippetsidiomsordinal

Python one-liner to print text converted from ASCII numbers?


The following command print text from it's ASCII representative.

python -c "print unichr(72)"

E.g.

[user@linux ~]$ python -c "print unichr(72)"
H
[user@linux ~]$

But this is only for a single character. If I have an ASCII string, let say 72 101 108 108 111 32 87 111 114 108 100 for Hello World, is it possible to convert it in Python in one line?

I've been trying the following commands but it didn't work.

[user@linux ~]$ python -c "print unichr(72)" "unichr(72)"
H
[user@linux ~]$ 

...

[user@linux ~]$ python -c "print unichr(72) unichr(72)"      
  File "<string>", line 1
    print unichr(72) unichr(72)
                          ^
SyntaxError: invalid syntax
[user@linux ~]$

...

[user@linux ~]$ python -c "print unichr(72)(72)"         
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: 'unicode' object is not callable
[user@linux ~]$ 

Solution

  • $ python -c 'print "".join(unichr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100))'
    Hello World
    

    How it works

    This generates a list of unicode characters:

    >>> [unichr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)]
    [u'H', u'e', u'l', u'l', u'o', u' ', u'W', u'o', u'r', u'l', u'd']
    

    This combines the list of characters into a string:

    >>> ''.join(unichr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100))
    u'Hello World'
    

    Python3 Version

    unichr no longer exists in python3. Instead, use:

    >>> print("".join(chr(i) for i in (72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)))
    Hello World