简体   繁体   中英

Python equivalent to echo -e?

Is there a python equivalent to echo -e ?

In other words, is there a built-in function to convert r"\\x50\\x79\\x74\\x68\\x6f\\x6e" to "Python" in Python?

Edit I added the 'r' prefix, to make sure everyone understands that I do not want the python interpreter to convert this. Rather, I want to convert that 24-character string to a 6-character one.

The correct way to do this, which I just found is

>>> a = r"\x50\x79\x74\x68\x6f\x6e"
>>> print a
\x50\x79\x74\x68\x6f\x6e
>>> a.decode('string_escape')
'Python'

Make sure you are escaping the backslashes (or using the raw 'r' prefix) when testing this!

References:

No conversion is necessary. They are already the same string

>>> "\x50\x79\x74\x68\x6f\x6e" == "Python"
True

If you actually have a different string "\\\\x50\\\\x79\\\\x74\\\\x68\\\\x6f\\\\x6e" which actually contains backslashes ( "\\x50\\x79\\x74\\x68\\x6f\\x6e" does not contain any backslashes), then you would do

>>> s
'\\x50\\x79\\x74\\x68\\x6f\\x6e'
>>> s.decode('string-escape')
'Python'

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