AnswerBun.com

Save string to file without converting newlines using Python

Stack Overflow Asked by Kleiton Kurti on November 29, 2020

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

One Answer

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'

Correct answer by Melvin Abraham on November 29, 2020

Add your own answers!

Related Questions

Vimeo offline video playback issue

0  Asked on September 26, 2020 by ipatel

         

How to print data from a few arrays

3  Asked on September 25, 2020 by protodimbo

   

why this.key is not working properly in javacript?

2  Asked on September 25, 2020 by carlos-daniel

 

Pass the dynamic variable when button is pressed

1  Asked on September 19, 2020 by francy

 

detect a table part from entire image in python

5  Asked on September 19, 2020 by suji

   

C# Change number of decimals show, but it always skips a number

0  Asked on September 18, 2020 by theoverly

   

Custom font bold weight not working in Dompdf

1  Asked on September 17, 2020 by user13286

   

How to use has one through in laravel?

0  Asked on September 17, 2020 by ahz

       

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir