1

How do i escape \n in a string in python.

How do i write out to stdin in python this string "abc\ndef" as one single input

Sys.stdout.write("abc\ndef")

current output

import sys

>>> sys.stdout.write("abc\ndef")
abc
def

I would like it to be abc\ndef

aceminer
  • 4,089
  • 9
  • 56
  • 104

2 Answers2

9

You should escape the backslash so that it's not treated as escaping character itself:

Sys.stdout.write("abc\\ndef")

Background

The backslash \ tells the parser that the next character is something special and must be treated differently. That's why \n will not print as \n but as a newline. But how do we write a backslash then? We need to escape it, too, resulting in \\ for a single backslash and \\n for the output \n.

Docs here, also see this SO question

Alternatively you can use "raw" strings, i.e. prefixing your strings with an r, to disable interpreting escape sequences is your strings:

Sys.stdout.write(r"abc\ndef")
m02ph3u5
  • 3,022
  • 7
  • 38
  • 51
7

As an alternative to escaping the backslash, you can disable backslash-escaping entirely by using a raw string literal:

>>> print(r"abc\ndef")
abc\ndef
Tom Dalton
  • 6,122
  • 24
  • 35