简体   繁体   中英

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)"

Eg

[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 ~]$ 
$ 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

怎么样

 python -c 'print "".join(unichr(int(c)) for c in "72 101 108 108 111 32 87 111 114 108 100".split(" "))'

Separate the unichr() calls with a + or , will work.

Example: python -c "print unichr(72)+unichr(73),unichr(65)" prints HI A

You can see + concatenates and , adds a space in between.

So, you can use the + operator between the unichr() function calls

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM