Home > Net >  Python pandas dataframe write \n as text to csv file
Python pandas dataframe write \n as text to csv file

Time:09-13

What I would like is to write the sentence "hello \n world\n." in a cell as it is, without "\n" being considered end of line, such that when I open it in a text editor I could see exactly "hello \n world\n.". How can I do that?

CodePudding user response:

You can use two \. So:

df.loc[cell] =  "hello \\n world\\n."

CodePudding user response:

In Python backslash is used as escape character. This means that inside string if you dont want to use special character such as newline character, you have put the backslash in front.

print("Hello \nWorld")
-> Hello
   World

print("Hello \\nWorld")
-> Hello \nWorld

CodePudding user response:

Use this way:

import pandas as pd
df = pd.DataFrame({'full_string':['hello \n world! \n', 'hello \nworld!\n']})


df = df.stack().str.replace('\n', '\\n', regex=True).unstack()


df.to_csv('hi.csv')

Output text:

,full_string
0,hello \n world! \n
1,hello \nworld!\n
  • Related