I am coming from C language
In book of Python it is given
among escape sequence
\ - New line in a multi-line string
\n - Line break
I am confused and unable to differentiate between the two.
I am coming from C language
In book of Python it is given
among escape sequence
\ - New line in a multi-line string
\n - Line break
I am confused and unable to differentiate between the two.
You have completely misread the book.
\
is not an escape sequence, and is not used on its own in strings. It is used in multi-line code.
\n
is a newline character in strings.
It is used for splitting a string which has a vast number of characters into multi lines as it is inconvenient to write in a single line. This is something that has effect in the code only.
This one on the other hand is a typical line break statement for printing something in a new line. The same thing we use in C and C++ languages. this is something that has effect in the output.
The book is confusing you by mixing two entirely different concepts.
\n
is an escape sequence in a string literal. Like other \single-character
and \xhh
or \uhhhh
escape sequences these work exactly like those in C; they define a character in the string that would otherwise be difficult to spell out when writing code.
\
at the end of a physical line of code extends the logical line. That is, Python will see text on the next line as part of the current line, making it one long line of code. This applies anywhere in Python code.
You can trivially see the difference when you print the results of strings that use either technique:
escape_sequence = "This is a line.\nThis is another line"
logical_line_extended = "This is a logical line. \
This is still the same logical line."
print(escape_sequence)
print(logical_line_extended)
This outputs
This is a line.
This is another line
This is a logical line. This is still the same logical line.
Note that the line breaks have swapped! The \n
escape sequence in the string value caused the output to be broken across two lines (the terminal or console or whatever is displaying the printed data, knows how to interpret a newline character), while the newline in the logical_line_extended
string literal definition is gone; it was never part of the string value being defined, it was a newline in the source code only.
Python lets you extend a line of code like this because Python defines how you delimit logical lines very differently from C. In C, you end statements with ;
, and group blocks of lines with {...}
curly braces. Newlines are not part of how C reads your code.
So, the following C code:
if (a) { foo = 'bar'; spam = 'ham'; }
is the same thing as
if (a) {
foo = 'bar';
spam = 'ham';
}
C knows where each statement starts and ends because the programmer has to use ;
and {...}
to delimit lines and blocks, the language doesn't care about indentation or newlines at all here. In Python however, you explicitly use newlines and indentation to define the same structure. So Python uses whitespace instead of {
, }
and ;
.
This means you could end up with long lines of code to hold a complex expression:
# deliberately convoluted long expression to illustrate a point
expr = 18 ** (1 / 3) / (6 * (3 + sqrt(3) * I) ** (1 / 3)) + 12 ** (1 / 3) * (3 + sqrt(3) * I) ** (1 / 3) / 12
The point of \
is to allow you to break up such a long expression across multiple logical lines by extending the current line with \
at the end:
# deliberately convoluted long expression to illustrate a point
expr = 18 ** (1 / 3) / (6 * (3 + sqrt(3) * I) ** (1 / 3)) + \
12 ** (1 / 3) * (3 + sqrt(3) * I) ** (1 / 3) / 12
So the \
as the last character on a line, tells Python to ignore the newline that's there and continue treating the following line as part of the same logical line.
Python also extends the logical line when it has seen an opening (
, [
or {
brace, until the matching }
, ]
or )
brace is found to close the expression. This is the preferred method of extending lines. So the above expression could be broken up across multiple logical lines with:
expr = (18 ** (1 / 3) / (6 * (3 + sqrt(3) * I) ** (1 / 3)) +
12 ** (1 / 3) * (3 + sqrt(3) * I) ** (1 / 3) / 12)
You can do the same with strings:
long_string = (
"This is a longer string that does not contain any newline "
"*characters*, but is defined in the source code with "
"multiple strings across multiple logical lines."
)
This uses another C string literal trick Python borrowed: multiple consecutive string literals form one long string object once parsed and compiled.
See the Lexical analysis reference documentation:
2.1.5. Explicit line joining
Two or more physical lines may be joined into logical lines using backslash characters (
\
)[.][...]
2.1.6. Implicit line joining
Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes.
The same documentation lists all the permitted Python string escape sequences.
Here is the response to your question:
Purpose of \n is basically used to give a line break as you mention too.
Example:
print("Hello\n")
print("Hi")
The output of the above would be like:
Hello
Hi
Purpose of \ is basically used to escape characters which have special meaning
Example: I have to print Hello\ in the output then the code will be like
print("Hello\\")
The output of the above code will be like:
Hello\
So bascially in order to print Hello\ in your output, you have to put two "\\" and this is the purpose of \ character (to escape special characters).
I hope this helps.
With "\" you can change line as you write your code. What I mean is that if you write a long line of code and you want to change line to see what you type. For example :
print("This is a demonstration of backslash.")
is the same as writing :
print("This is a demonstration \
of backslash")
On the other hand with "\n" you can change line in what you want to print. For example, when you write:print("this is an \nexample")
, it will print "this is an"(changes line) "example".
Use \n to have your output go to the next line.
print('Hello \nworld!')
Hello
world!
Use the back slash with a character that has a meaning to Python when you want that character to appear in the printed output.
print('It\'s cold outside')
It's cold outside
I hope this helps.
As excellently answered by @Jimmy I further give the following examples to make the matter more clear.
Case 1:
>>> var1 = "Adolf Hitler was a German dictator. He started the second world war."
>>> print(var1)
Adolf Hitler was a German dictator. He started the second world war.
>>>
Case 2:
>>> var2 = "Adolf Hitler\
... was a German dictator.\
... He started the\
... second world war."\
...
>>> print(var2)
Adolf Hitler was a German dictator. He started the second world war.
>>>
Case 3:
>>> var3 = "Adolf Hitler\nwas a German dictator.\nHe started the\nsecond world war."
>>> print(var3)
Adolf Hitler
was a German dictator.
He started the
second world war.
>>>
Case 4:
>>> var4 = "Adolf Hitler\
... \nwas a German dictator.\
... \nhe started the\
... \nsecond world war."\
...
>>> print(var4)
Adolf Hitler
was a German dictator.
he started the
second world war.
>>>
There is also another point which @Jimmy has not mentioned. I have illustrated it by the following two examples -
Example 1:
>>> var5 = """
... This multi-line string
... has a space at the top
... and a space at the bottom
... when it prints.
... """
>>> print(var5)
This multi-line string
has a space at the top
and a space at the bottom
when it prints.
>>>
Example 2:
>>> var6 = """\
... This multi-line string
... has no space at the
... top or the bottom
... when it prints.\
... """
>>> print(var6)
This multi-line string
has no space at the
top or the bottom
when it prints.