[Tutor] Interactive escape sequences
Steven D'Aprano
steve at pearwood.info
Tue Jan 14 14:35:20 CET 2014
On Tue, Jan 14, 2014 at 02:42:07AM -0500, Christian Alexander wrote:
> Hello Tutorians,
>
> Why does the interactive prompt not recognize escape sequences in strings?
> It only works correctly if I use the print function in python 3.
>
> >>> "Hello\nWorld"
> "Hello\nWorld"
I'm afraid that you are misinterpreting what you are seeing. Regardless
of whether you use the interactive prompt or not, or whether you print
the string, the string "Hello\nWorld" contains the words "Hello" and
"World" separated by a newline.
What happens when you display the string?
When you use print, it gets printed to the screen, which means that
newline actually causes a new line. In addition, tabs cause the text to
be indented. So:
py> s = "Hello\nWorld\t!"
py> print s
Hello
World !
But in addition to just printing the string, we can print the
*representation* of the string, which shows control characters in
escaped form and includes quotation marks:
py> print repr(s)
'Hello\nWorld\t!'
You'll notice that the repr() of the string is just like what you typed
as a string literal, except that I typed double quotes " and Python uses
single quotes ' by default.
What happens if we don't use print, but just enter the string?
py> s
'Hello\nWorld\t!'
The interactive interpreter chooses to display the repr() of the string,
rather than print the string. The reason for this is that, in general,
it is more useful to see the repr() while debugging or experimenting
interactively, and if you wish to the see the printed version of the
string, it's easy enough to use print.
Note: my examples above are using Python 2. In Python 3, you need to
use round brackets after the print, e.g. "print(s)".
--
Steven
More information about the Tutor
mailing list