0

I want to save the following string into a file using Python. The string includes \n which I don't want to be converted into a new line. Here is my code:

text = 'hello "\n" world'
file = open("file.js", "w")
file.write(text)
file.close()

When I open file.js I get the following output (which is expected):

hello "
" world

Is there any way to save the file without the newlines being forced to be be converted? My desired output to the file would be:

hello "\n" world
  • 1
    Check this: https://stackoverflow.com/questions/41063524/write-escaped-character-to-file-so-that-the-character-is-visible – M.Soyturk Nov 06 '20 at 12:10

1 Answers1

4

You can achieve this by escaping backslashes (\\). So, you can just escape the newline character like:

text = 'hello "\\n" world'

You can also use something called raw-strings which automatically escapes the backslashes for you. These are strings that precede with an r:

text = r'hello "\n" world'

Output


When written to a file, you will get the following, without any newline character in the middle:

'hello "\n" world'
Melvin Abraham
  • 2,870
  • 5
  • 19
  • 33