Strings

Bengt Richter bokr at oz.net
Thu Apr 21 21:37:13 EDT 2005


On Thu, 21 Apr 2005 10:09:59 -0400, Peter Hansen <peter at engcorp.com> wrote:

>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.
When I wonder how many characters are actually in a_string, I find
list(a_string) helpful, which BTW also re-reprents equivalent escapes
in a consistent way, e.g., note \n's at the end:

 >>> s= 'escapes \\n \n \x0a \012'
 >>> list(s)
 ['e', 's', 'c', 'a', 'p', 'e', 's', ' ', '\\', 'n', ' ', '\n', ' ', '\n', ' ', '\n']

OTOH, don't try that with '\a':

 >>> list('\a \x07 \07')
 ['\x07', ' ', '\x07', ' ', '\x07']

Why not like \n above or like \t

 >>> list('\t \x09 \011')
 ['\t', ' ', '\t', ' ', '\t']

Is this fixed by now? It's not news ;-)

 >>> '\a'
 '\x07'

Regards,
Bengt Richter



More information about the Python-list mailing list