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

169,679

Solution 1

Use repr

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

Solution 2

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

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

Share:
169,679
wolfgang
Author by

wolfgang

Updated on June 13, 2020

Comments

  • wolfgang
    wolfgang almost 4 years

    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)

  • Gregory Saxton
    Gregory Saxton over 6 years
    Thanks. This is the only thing that worked for my particular purpose -- printing out a PANDAS dataframe.to_latex() and adding in \noalign and \vskip.
  • Mordechai
    Mordechai about 6 years
    isn't it the other way around - .replace("\\n","\n")?
  • Amos Wazana
    Amos Wazana about 6 years
    This is a better solution when replacing strings in languages with special characters (chinese, korean, even letters with an umlaut and stuff like that). The repr solution causes these characters to change to their encoded state.