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
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'
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
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP