wolfgang
wolfgang

Reputation: 7789

Print "\n" or newline characters as part of the output on terminal

I'm running Python on terminal

Given a string string = "abcd\n"

I'd like to print it somehow so that the newline characters '\n' in abcd\n would be visible rather than go to the next line

Can I do this without having to modify the string and adding a double slash (\\n)

Upvotes: 108

Views: 267193

Answers (3)

Gildas
Gildas

Reputation: 1128

Another suggestion is to do that way:

string = "abcd\n"
print(string.replace("\n","\\n"))

But be aware that the print function actually print to the terminal the "\n", your terminal interpret that as a newline, that's it. So, my solution just change the newline in \ + n

Upvotes: 13

Michel85
Michel85

Reputation: 317

If you're in control of the string, you could also use a 'Raw' string type:

>>> string = r"abcd\n"
>>> print(string)
abcd\n

Upvotes: 18

Bhargav Rao
Bhargav Rao

Reputation: 52071

Use repr

>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'

Upvotes: 177

Related Questions