114

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

4 Answers 4

186

Use repr

>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'
Sign up to request clarification or add additional context in comments.

1 Comment

This adds single quotes, which may not be always the best.
19

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

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

Comments

14

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 Comments

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.
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.
0

If you want to print exactly \n in python , you should do this: \\n

Example :

b= "\\n"
print(b)

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.