8

I am currently taking a course in python. When talking about escape sequences they told about "\n" is used for printing strings in new line. But when it is used in the following ways why I am getting a different output

>>> st = "Hello\nWorld"
>>> st
'Hello\nWorld'

But if I do

>>> print st
Hello
World
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Srividya
  • 119
  • 1
  • 1
  • 9
  • 2
    Also see [Difference between `__str__` and `__repr__` in Python](http://stackoverflow.com/q/1436703/4014959) – PM 2Ring Jul 18 '15 at 08:54
  • Another related link: [Understanding repr( ) function in Python](http://stackoverflow.com/q/7784148/4014959) – PM 2Ring Jul 18 '15 at 09:05

2 Answers2

12

There are two functions that give an object's string representation, repr() and str(). The former is designed to convert the object to as-code string, while the latter gives user-friendly string.

When you input the variable name in the command line, repr() is used, and \n character is shown as \n (as-code). When you use print, str() is used, and \n is shown as a new line (user-friendly).


By the way, str is a bad name for a variable, as it's the same as the built-in.

user590028
  • 11,364
  • 3
  • 40
  • 57
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
0

When you do

st

It is somewhat similar to

"\n"

where you expect the string \n in return, and not a new line.

In both cases, the print function is not called which can actually process what \n really means. That's why print 'Hello\nWorld' gives different output than

>>> 'Hello\nWorld'
Himanshu Mishra
  • 8,510
  • 12
  • 37
  • 74