2

How do I print a string that has \n in it without it actually going to a new line? For example, how do I do:

print("You can use \n for a new line") 

without it doing a line break?

2
  • Only a new line? Or all escaped characters? Commented Jan 27, 2018 at 15:23
  • I want to print \n without it going to a new line. Commented Jan 27, 2018 at 15:23

1 Answer 1

7
print(r"You can use \n for a new line") 

or

print("You can use \\n for a new line") 

The first option (putting the r in front of the string) causes all the backslashes in the string to be simply interpreted as a backslash character instead of an escape character to do something special (see https://stackoverflow.com/a/2081708/6735980 for more info on that). This is especially useful, for example, if you have multiple instances of \n in the string and you want them all to simply be interpreted as exactly those two characters instead of a newline.

The second option (using a double backslash) causes python to specifically interpret that part of the string as a single backslash. This is useful if you want more control than what the first solution offers (for example, if within the same string you have one place where you really just want to print \n, and a different part in the same string where you do want to use a newline).

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.