I have a list of sentences, I need to add new line character and save in text file as the following format. Note: I don't need new line character I want to keep in the given string format. I just want to keep \n and not get new line in text file list:['Hi','I am xyz'] String Format:'Hi\nI am xyz' If someone knows please let me know.
CodePudding user response:
In raw strings escape characters such as \n
won't be parsed as such, but as regular text.
CodePudding user response:
The default behavior of Python requires you to escape the backslash so that it's not interpreted as a newline:
>>> print("\n")
>>> print("\\n")
\n
If you string contains more newlines, having many backslashes doubled might hurt readability. In such case, you can use the raw string literals to save you escaping:
>>> print(r"\n")
\n
Keep in mind that raw string literals cannot end with a backslash!
>>> print(r"\")
File "<stdin>", line 1
print(r"\")
^
SyntaxError: unterminated string literal (detected at line 1)
You can read more about this in the lexical analysis part of Python docs: https://docs.python.org/3/reference/lexical_analysis.html