Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

working of \n in python [duplicate]

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
like image 705
Srividya Avatar asked Jul 18 '15 08:07

Srividya


1 Answers

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.

like image 89
Yu Hao Avatar answered Oct 07 '22 05:10

Yu Hao