[英]Python pandas dataframe write \n as text to csv file
我想写一句“hello \n world\n”。 在一个单元格中,没有“\n”被认为是行尾,这样当我在文本编辑器中打开它时,我可以准确地看到“hello \n world\n.”。 我怎样才能做到这一点?
在 Python 中,反斜杠用作转义字符。 这意味着如果您不想在字符串内部使用换行符等特殊字符,则必须将反斜杠放在前面。
print("Hello \nWorld")
-> Hello
World
print("Hello \\nWorld")
-> Hello \nWorld
使用这种方式:
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 文字:
,full_string
0,hello \n world! \n
1,hello \nworld!\n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.