2 may
2021

Why don't escape sequences work in tuples

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

COMENTARIOS wjandrea

The escape sequences do work. x is being printed as a tuple because it is a tuple. If you want to join its elements, use str.join(), or have print() join it for you.

>>> x = ('a\n', 'b\n', 'c\n')
>>> x
('a\n', 'b\n', 'c\n')
>>> ''.join(x)
'a\nb\nc\n'
>>> print(''.join(x))
a
b
c

>>> print(*x, sep='')
a
b
c

>>>

Meanwhile, y is a string due to string literal concatenation

>>> y = ("a\n" "b\n" "c\n")
>>> y
'a\nb\nc\n'
>>> print(y)
a
b
c

>>> MarianD

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 Anshul Singh Suryan

By Default \n takes a new line no matter what you are storing, the interpreter understands this thing that you want to store some values in the next line. So, that's the way it printed like that. M? D????

Try this

print("a{nl}"
"b{nl}"
"c".format(nl="\n"))

DEJA TU COMENTARIO

© 2017 website by Rubit Corporation