Strings

Peter Hansen peter at engcorp.com
Thu Apr 21 10:09:59 EDT 2005


Dan wrote:
> I've having trouble coming to grip with Python strings.
> 
> I need to send binary data over a socket.  I'm taking the data from a
> database.  When I extract it, non-printable characters come out as a
> backslash followed by a three numeric characters representing the
> numeric value of the data.  I guess this is what you would call a raw
> Python string.  I want to convert those four characters ( in C-think,
> say "\\012" ) into a single character and put it in a new string.

Does this help?

 >>> s = 'foo \\012 bar'
 >>>
 >>> s.decode('string-escape')
'foo \n bar'
 >>> print s.decode('string-escape')
foo
  bar
 >>>

Note that the \n in the first one is because I didn't
*print* the result, but merely allowed the interpreter
to call repr() on it.  repr() for a newline is of course
backslash-n, so that's what you see (inside quotation marks)
but the string itself has only 9 characters in it, as
you wished.

-Peter



More information about the Python-list mailing list