繁体   English   中英

Python pandas dataframe 将 \n 作为文本写入 Z628CB5675FF524F3E719B7AA2E

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM