interpretation of special characters in Python

Peter Otten __peter__ at web.de
Mon Jul 7 10:10:14 CEST 2008


Peter Pearson wrote:

> On Sun, 06 Jul 2008 23:42:26 +0200, TP <Tribulations at Paralleles.invalid>
> wrote:
>>
>> $ python -c "print '\033[30;44m foo \033[0m'"
> [writes an escape sequence to stdout]
> 
>> $ echo -e $esc$ColorBlackOnDarkblue foo $esc$ColorReset
> [also writes an escape sequence to stdout]
> 
>> $ echo -n $esc$ColorBlackOnDarkblue foo $esc$ColorReset
>> \033[30;44m foo \033[0m
> 
> [snip, shuffle]
>> $ export esc="\033"
>> $ export ColorBlackOnDarkblue="[30;44m"
>> $ export ColorReset="[0m"
>>
>> import os
>> Color = os.environ['ColorBlackOnDarkblue']
>> ColorReset = os.environ['ColorReset']
>> Esc = os.environ['esc']
>> print '%s%s%s%s%s' % (Esc, Color, " foo ", Esc, ColorReset)
> [snip]
>> $ python color.py
>> \033[30;44m foo \033[0m
> 
> The string "\033" is 4 characters long. Your shell variable
> "esc" is 4 characters long.  Your Python program prints
> those four characters.  You want it to re-interpret those 4
> characters into a single escape character.
> 
> One of this group's regular participants can (I hope) tell
> us three breathtakingly elegant ways to do that.  I'm sorry
> I can't.
> 
> When you run echo, it recognizes the 4-character "esc" as a
> convention for representing a single character, and performs
> the re-interpretation for you.  When you tell python
> "print '\033[30;44m foo \033[0m'", python interprets
> the "\033" as a single character.

Peter Pearson's explanation is spot-on. You get the 4-character sequence
instead of the escape code chr(27).

$ export esc="\033"
$ python
Python 2.5.1 (r251:54863, Mar  7 2008, 03:39:23)
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ["esc"]
'\\033'
>>> print _
\033

If you want to interpret "\\033" as "\033" you have to perform the
conversion explicitly. Fortunately there already is an encoding that
understands these escape sequences for characters:

>>> esc = os.environ["esc"].decode("string-escape")
>>> esc
'\x1b'
>>> print "%s[30;44malles so schoen bunt hier%s[0m" % (esc, esc)
alles so schoen bunt hier

Peter



More information about the Python-list mailing list