105

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)

0

3 Answers 3

170

Use repr

>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'
1
  • 1
    This adds single quotes, which may not be always the best.
    – AnnShress
    Commented Nov 7, 2022 at 19:47
18

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

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

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

2
  • 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. Commented Aug 2, 2017 at 19:56
  • 1
    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. Commented Feb 14, 2018 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.