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
Author by
wolfgang
Updated on June 13, 2020Comments
-
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'
inabcd\n
would be visible rather than go to the next lineCan I do this without having to modify the string and adding a double slash (
\\n
) -
Gregory Saxton over 6 yearsThanks. 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 about 6 yearsisn't it the other way around - .replace("\\n","\n")?
-
Amos Wazana about 6 yearsThis 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.