new line

Peter Hansen peter at engcorp.com
Mon Aug 29 22:12:27 EDT 2005


Kuljo wrote:
> Kuljo wrote:
>>I'm so sorry to bore you with this trivial problem. Allthou: I have string
>>having 0x0a as new line, but I should have \n instead.

> I have found this in the meantime:
>>>>nl="\\"+"n"

Note: this is unnecessary.  You could just do nl='\\n' instead, and you 
don't need the variable "nl" either, which by the way is confusingly 
named.  Your variable "nl" is actually bound to the two character 
sequence \ followed by n instead of a "newline".  Is that really what 
you wanted?

>>>>text_new=replace(text_old, chr(10), nl)

This use of replace() is deprecated.  Use text_old.replace() instead.

> It works.

For some definitions of "works".  This only works if you wanted the 
*single* character represented by '\x0a' to turn into the *two* 
characters backslash-followed-by-letter-n.  The following you might find 
instructive:

 >>> old = 'some\x0atext'
 >>> old
'some\ntext'
 >>> print old
some
text
 >>> old.encode('string-escape')
'some\\ntext'
 >>> print old.encode('string-escape')
some\ntext

This will turn other control characters into their equivalent 
two-character escaped representation as well, such as \t and \r, as 
necessary.

-Peter



More information about the Python-list mailing list