Why dont the escape sequences work in tuples when printed
x = ("a\n", "b\n", "c\n")
y = ("a\n" "b\n" "c\n")
print (x)
print(y)
Why does it print(x) return ('a\n', 'b\n', 'c\n')
and print (y)
a
b
c
Because ("a\n", "b\n", "c\n")
is a tuple, but ("a\n" "b\n" "c\n")
is a string:
("a\n" "b\n" "c\n")
is the same as "a\n" "b\n" "c\n"
what is in turn the same as "a\nb\nc\n"
.
(The "Hello, world."
string literal is possible to write as "Hel" "lo, wor" "ld."
, no +
between parts.)
Now, the print()
function prints a non-string object (as e.g. your tuple) converting it first to a string applying its .__str()__
method (which produces the same result as the standard function str()
).
The result of str(("a\n", "b\n", "c\n"))
is the string "('a\\n', 'b\\n', 'c\\n')"
— no newline characters in it, as you may see, it consists of these 21 characters:
(
'
a
\
n
'
,
'
b
\
n
'
,
'
c
\
n
'
)
By contrast to this string representation of your tuple, your string ("a\n" "b\n" "c\n")
alias "a\nb\nc\n"
consist of 6 characters, and 3 of them are newline characters:
a
\n
b
\n
c
\n