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

PythonStringNewline

Python Problem Overview


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)

Python Solutions


Solution 1 - Python

Use repr

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

Solution 2 - Python

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

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

Solution 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwolfgangView Question on Stackoverflow
Solution 1 - PythonBhargav RaoView Answer on Stackoverflow
Solution 2 - PythonMichel85View Answer on Stackoverflow
Solution 3 - PythonGildasView Answer on Stackoverflow