Typing \n in strings

Peter Hansen peter at engcorp.com
Sat Apr 3 22:10:38 EST 2004


Edward Diener wrote:

> Python 2.3.3 on Win2K. In the Python tutorial it says that typing \n in
> string literals is the new-line character. I open the interpreter and type a
> string with a \n in it but instead of outputting a string with a new line,
> it outputs the \n as literal characters of the string. Is the tutorial
> wrong, is the interpreter broken, or what is happening ?

Notice that there are also quotation marks around that string?  What
you are seeing is _not_ the string itself, but a printable
representation of the string.  Since it contains a newline, which is
not "printable" (by this definition, anyway) it converts it to \n
again.  Trust that the string really does contain the ASCII LF
character (byte value 10) however.  To prove it, and see the real
string, just print it:

 >>> 'test\nme'
'test\nme'
 >>> print 'test\nme'
test
me

Does that help?

Remember always that the interactive interpreter shows you the
expression using the repr() call, which with strings will give
you a representation that makes it clearer what non-printable
characters are contained therein.  Here's something that might
clear up any remaining questions:

 >>> print repr('test\nme')
'test\nme'

(Or, it might just raise more questions in your mind...
experimenting a little more should answer most of them. :-)

-Peter



More information about the Python-list mailing list