I'm sort of mystified by the print hex to char conversion

Dave Angel davea at ieee.org
Sat Apr 18 22:48:22 EDT 2009


grocery_stocker wrote:
> I'm just really not seeing how something like x63 and/or x61 gets
> converted by 'print' to the corresponding chars in the following
> output...
>
> [cdalten at localhost oakland]$ python
> Python 2.4.3 (#1, Oct  1 2006, 18:00:19)
> [GCC 4.1.1 20060928 (Red Hat 4.1.1-28)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>   
>>>> print '\x63had'
>>>>         
> chad
>   
>>>> print '\x63h\x61d'
>>>>         
> chad
>   
>>>> print "\x63had"
>>>>         
> chad
>   
>>>> print "\x63h\x61d"
>>>>         
> chad
>   
>
> Does print just do this magically?
>
>   
print() isn't doing anything special with these strings.  It's just 
sending the characters to stdout.   The question is what are the characters.

Whenever you're defining a quote literal in your code, there are rules 
about how characters are interpreted on their way to the string.  And 
these rules are different for ascii strings, for unicode strings, and 
for raw strings (all prefixes to the leading quote sign.  I'll just talk 
about the ascii strings.

In order to let you enter characters into a string that would otherwise 
be difficult (like newline, which has a special meaning, or backspace, 
which is tricky to type in most text editors), the backslash is defined 
as an escape character.  Whatever follows the backslash is interpreted 
specially.  One case is the \n, which represents a newline.  Another is 
\t, which represents tab.  Another is \xdd  which is used to represent 
an arbitrary code, given its hex representation.  There are others.





More information about the Python-list mailing list